Home > Blockchain >  Why is my class variable not changing for all instances?
Why is my class variable not changing for all instances?

Time:11-06

I wanted to learn about classes and don't understand this:

class MyClass:

    var = 1


one = MyClass()
two = MyClass()

print(one.var, two.var) # out: 1 1
one.var = 2

print(one.var, two.var) # out: 2 1

I though class variables are accessible by all instances, but why doesn't it change for all of them?

CodePudding user response:

It doesn't change for all of them because doing this: one.var = 2, creates a new instance variable with the same name as the class variable, but only for the instance one. After that, one will first find its instance variable and return that, while two will only find the class variable and return that.

To change the class variable I suggest two options:

  1. create a class method to change the class variable (my preference)

  2. change it by using the class directly

class MyClass:
    var = 1

    @classmethod
    def change_var(cls, var): 
        cls.var = var


one = MyClass()
two = MyClass()

print(one.var, two.var) # out: 1 1

one.change_var(2)  # option 1
print(one.var, two.var) # out: 2 2

MyClass.var = 3     # option 2
print(one.var, two.var) # out: 3 3

CodePudding user response:

Assignment to an attribute via an instance always creates/updates an instance variable, whether or not a class attribute of the same name exists. To update a class attribute, you must use a reference to the class.

>>> type(one).var = 2
>>> print(one.var, two.var)
2 2

In practice, type(one) might return the wrong class to update a particular class attribute, but also in practice, you don't need to change class attributes when you only have an instance of the class available.

  • Related