I'm confused about this behavior,
def calc():
print ("function .. calculating")
class Calc:
print ("Class .. calculating")
Which generates this output:
Class .. calculating
Why the code inside a class gets executed even if we didn't call it or create an object, while the code inside a function doesn't get executed until we call it ?
CodePudding user response:
That statement is not part of any method like __init__
or any method inside the class. As this statement is not a part of any method, the interpreter executes it before invoking the __init__
method (implicit in this case). Invoking the __init__
method means when the __init__
is called when you create an object of this class. That's why this prints it out.
Also another nice point, this would be executed multiple times when you instantiate the object. Because it is only when the interpreter is getting the class definition it executes that once. (From a discussion with Iain Shelvington)
It would be more clear from this output.
class Calc:
print ("Class .. calculating")
print(ab) #throws error
def __init__(self):
print('init')
In this case, if ab
is not used earlier then it will throw you error. Very important thing is: the namespace it belongs to, check this:
class Calc:
print ("Class .. calculating")
ab=2
def __init__(self):
print('init')
print(ab) #throws error
Now it will again throw error. Since it is declared inside the class. But you can instantiate the object of the class and access it as something that is part of the class scope.
class Calc:
print ("Class .. calculating")
ab=2
def __init__(self):
print('init')
calc = Calc()
calc.ab # 2
You can check this for further reference. I want to just highlight the subtlety involved in this scope
When a class definition is left normally (via the end), a class object is created. This is basically a wrapper around the contents of the namespace created by the class definition; we’ll learn more about class objects in the next section. The original local scope (the one in effect just before the class definition was entered) is reinstated, and the class object is bound here to the class name given in the class definition header (ClassName in the example).
CodePudding user response:
I totally agree with Tim Roberts. I'm not expert here but for specific below use case, the behavior is useful.
class Foo:
bar = 'Baz'
print(Foo.bar)
This way, you can store some data and need not to instantiate it to use the underlying data. However, if you want to use it on class instance, it is also available.
f = Foo()
print(f.bar)
CodePudding user response:
That is how the language is designed. The class body is executed when the class is defined. You can read more at docs: 9.3.1. Class Definition Syntax