1

I have the following code in Python 3:

class x():
    var = 0

x1 = x()
x2 = x()
print(x.var) #0
print(x1.var) #0
print(x2.var) #0

But if I change the attribute var for one instance, it change only for this instance:

x1.var = 1
print(x.var) #0
print(x1.var) #1
print(x2.var) #0

I would like the result to be:

x1.var = 1
print(x.var) #1
print(x1.var) #1
print(x2.var) #1
khelwood
  • 55,782
  • 14
  • 81
  • 108
Hippolyte BRINGER
  • 792
  • 1
  • 8
  • 30
  • 2
    If you want to alter the class variable `x.var`, use `x.var = 1`. – khelwood Feb 07 '20 at 16:23
  • 2
    You may have a look at this other [SO question](https://stackoverflow.com/questions/27481116/how-to-declare-a-static-attribute-in-python) – Romain F Feb 07 '20 at 16:27
  • If you want `x1.var = ...` to change a *class* attribute, you'll need to define a [setter](https://docs.python.org/3/library/functions.html#property) that explicitly sets the *class* attribute. – deceze Feb 07 '20 at 16:30

2 Answers2

1

An instance attribute can shadow a class attribute of the same name. If you want to change a class attribute via an instance, you have to do so explicitly, by getting a reference to the class. Otherwise, you are just creating a new instance attribute, rather than updating the class attribute.

class X:
    var = 0

x1 = X()
x2 = X()
type(x1).var = 1
chepner
  • 497,756
  • 71
  • 530
  • 681
0

Building on the comment of @khelwood, you can change the class attribute by referencing instance.__class__:

class x():
    var = 0

x1 = x()
x2 = x()
print(x.var) #0
print(x1.var) #0
print(x2.var) #0

x1.__class__.var = 1
print(x.var) #1
print(x1.var) #1
print(x2.var) #1
jkr
  • 17,119
  • 2
  • 42
  • 68