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...
解决方案
This odd behaviour happens because your print("Middle",x,y) is not inside a definition of a function, so it gets called before print("Out",x,y).
Your code is equivalent to:
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)
Whose output will be:
Middle 5 3
Out 5 3
In 1 2 1 2
One of the possible ways to correct this is to define print("Middle",x,y), say within the constructor.
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 you will then get is:
Out 5 3
In 1 2 1 2
Middle 1 2