Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialise a class variable with __init__()?

Tags:

python

oop

class

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
like image 330
Cupitor Avatar asked Sep 15 '25 23:09

Cupitor


1 Answers

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.

like image 169
falsetru Avatar answered Sep 18 '25 16:09

falsetru