Search code examples
pythonvariables

Strange behavior when python class variables and instance variables overlap


class TestClass():
    class_v = 0
    
    def __init__(self) -> None:
        self.class_v += 1
        TestClass.class_v += 1
        
        
        
print(TestClass.class_v) # 0

class_a = TestClass()
class_b = TestClass()

print(f'class_a.class_v = {class_a.class_v}') # 1
print(f'class_b.class_v = {class_b.class_v}') # 2
print(TestClass.class_v) # 2

In the python code above, when the names of the class variable and instance variable are the same, two instances were created with the same class, but the values are different when the variable is imported. If it is an instance variable, both must be 1, and if it is a class variable, both must be 2. How does python work?

# ex
TestClass.class_v += 1
self.class_v += 1

If you change the order of the code blocks above, 2 and 3 are output instead of 1 and 2.


Solution

  • It may help to think of them as "attributes", not "variables". I'm guessing your confusion comes from thinking that the class's class_v and the instance's class_v are the same variable. They are not.

    The class and the instance are two different objects, each with their own attributes, but instances can inherit attributes they haven't been assigned from their class. In self.class_v += 1, self doesn't have a class_v yet, so it retrieves a value from TestClass.class_v, then assigns the new value to self.class_v. In TestClass.class_v += 1, TestClass already has its own class_v, so the retrieval and assignment both deal with the same attribute.