Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my class variable not changing for all instances?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading