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?
Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.
Create Class VariablesA class variable is declared inside of class, but outside of any instance method or __init__() method. By convention, typically it is placed right below the class header and before the constructor method and other methods.
In C++, class variables are initialized in the same order as they appear in the class declaration.
The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.
At the moment the module is imported
test.py
:
def x():
print('x')
class A:
x = x()
then
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With