if i have a python class and it has static attributes and i instantiated two object from the class, will the static attributes be created twice (once for every object) or will it be saved in a static memory that is shared across objects?
I know in C there is a type of memory that includes all the static attributes and methods, but it wasn't clear in python if it is the case.
CodePudding user response:
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.