Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of execution with python class

I was writing a small python script to understand a concept and got another confusion. Here's the code -

x = 5
y = 3

class Exp(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

        print("In",x, y, self.x, self.y)
    print("Middle",x,y)

print("Out",x,y)

Exp(1,2)

The output is -

Middle 5 3
Out 5 3
In 1 2 1 2

Now, my concept was python interpreter starts reading and executing the code from the first line to last line. It executes the code inside a class only when it is "called", not when it is defined. So, the output should print "Out" first. But here it is printing "Middle" first. This should not happen, as python interpreter when first encounters "Middle" - it is within the definition, and thus should not be executed at that time. It should be executed only after reading the last line of code where the class "Exp" is called.

I searched on Google and StackOverflow for the solution but couldn't find one explaining it for the class.

Kindly help me understand where I'm getting it wrong...

like image 577
Arnb Avatar asked Oct 28 '25 15:10

Arnb


1 Answers

Your doubt is right. I had the same doubt like 6 months back and a friend of mine helped me figure the answer out.

print("Middle",x,y)

The above statement does not belong to any method. It belongs to the class Exp. The __init__() method is executed when an object is created and is internally called by the Python interpreter when an object is instantiated from your end. Since the above statement is not a part of any method, the interpreter executes it before invoking the __init__ method. Since variables x and y are both available in the scope of class Exp, it isn't considered an error and the interpreter executes it.

If you remove the declarations of variables x and y, you will see a NameError like below.

Traceback (most recent call last):
  File "trial.py", line 9, in <module>
    print("Middle",x,y)
NameError: name 'x' is not defined

And this is because x and y are not even created from the class Exp's perspective.

like image 76
sameera sy Avatar answered Oct 30 '25 06:10

sameera sy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!