As I understand, a class property can be used in a sense as the static variable for Python. I have a class and I would like to set this static variable during the first run of __init__()
, i.e. when the first object is being created and to keep it like that. Not to update it each time. What should I do exactly? Even setting a flag doesn't help.
class A():
foo=None
foo_set_flag=False
def __init__(self,arg_foo):
if not self.foo_set_flag:
self.foo=arg_foo
foo_set_flag=True
a=A(12)
b=A(13)
print a.foo
print b.foo
which gives:
12
13
and of course I expect
12
12
Use ClassName.attribute_name
to access class attribute:
class A:
foo = None
foo_set_flag = False
def __init__(self, arg_foo):
if not A.foo_set_flag:
A.foo = arg_foo
A.foo_set_flag = True
a=A(12)
b=A(13)
print a.foo # -> 12
print b.foo # -> 12
self.foo = ...
creates a new instance attribute. Reading self.foo
will access class attribute only if there is no instance attribute foo
, otherwise it access the instnace variable foo
.
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