pythonoopinstanceclass-variables

Why is the Class variable not updating for all its instances?


I'm learning 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 thought that class variables are accessible by all instances, why is the Class variable not updating for all its instances?


Solution

  • 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