I've come up with some code to explain what happens. The output will show the order in which code is executed.
It will show how the class attributes are created whilst the class is being defined.
(Note that class Report
is just a helper here whose only job is to have the side-effect of printing something each time an instance is created)
print('First line.')
class Report:
def __init__(self, name):
self.name = name
print(f'Reporting name:{name}')
def __str__(self):
return f'Report named:{self.name}'
print('Before Klass')
class Klass:
i = Report('i')
j = Report('j')
def __init__(self, name):
self.k = Report(name)
def main():
print('Starting main()')
x = Klass('x')
y = Klass('y')
print(x.i, x.j)
print(y.i, y.j)
if __name__ == '__main__':
print('Above are the "static" allocations')
print()
main()
print('Done')
Output:
First line.
Before Klass
Reporting name:i
Reporting name:j
Above are the "static" allocations
Starting main()
Reporting name:x
Reporting name:y
Report named:i Report named:j
Report named:i Report named:j
Done
Note that if Klass
were in a different module and you were to have something like: from Klass import Klass
as the first line, then i
and j
would be printed first.