Search code examples
pythonattributeslanguage-lawyerinstance-variablesclass-attributes

How to revert an instance to use the class attribute instead of the shadowing instance attribute?


If I have a class, and two instances of it:

class Foo:
    var = 1

a = Foo()
b = Foo()

Both of the instances' var attributes reflect the value I will set for Foo:

Foo.var = 2
print(a.var)  # 2
print(b.var)  # 2

But when I then set var for just a, a.var isn't anymore "in sync" with Foo.var:

a.var = 3
Foo.var = 4
print(a.var)  # 3
print(b.var)  # 4

Can I somehow "revert" this without creating a new instance so that a.var will once again reflect the value of Foo.var?

The obvious attempt doesn't (obviously) work, since integers are not references:

a.var = Foo.var
print(a.var)  # 4
Foo.var = 5
print(a.var)  # 5

Solution

  • The instance attribute can just be deleted and then a will once again use the var defined in Foo:

    del a.var
    Foo.var = 6
    print(a.var)  # 6