Consider the following Python 3 code:
class A:
b = LongRunningFunctionWithSideEffects()
When will LongRunningFunctionWithSideEffects() be called? At the moment the module is imported? Or at the moment the class is first used in some way?
Consider the following Python 3 code:
class A:
b = LongRunningFunctionWithSideEffects()
When will LongRunningFunctionWithSideEffects() be called? At the moment the module is imported? Or at the moment the class is first used in some way?
The code inside a class runs when the class statement is encountered - ie. during the import itself.
This is because, unlike in Java or C# class definitions, Python class statements are actually executable code.
class A:
print("I'm running!") # yup, code outside a method or field assignment!
b = print("Me too!")
print("Wait for me!")
The result is neatly in order of execution:
I'm running!
Me too!
Wait for me!
It is done at the time of import. These are called static variables and are defined at the class level. These variables are created 1 per class and NOT 1 per object. They are part of loading the class which happens at the time of import.
Following is an example:
classA.py
class A:
print("Printing before Static Variable Creation")
class_var = 1
def __init__(self):
instance_var = 2
main.py
from classA import A
Printing before Static Variable Creation
print('Printing Class Variable Value : ',A.class_var)
Printing Class Variable Value : 1
print(A.__dict__)
{'module': 'classA', 'class_var': 1, 'init': function classA.A.init(self), 'dict': attribute 'dict' of 'A' objects, 'weakref': attribute 'weakref' of 'A' objects, 'doc': None}