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
3
  • 2
    If you want to alter the class variable x.var, use x.var = 1. Commented Feb 7, 2020 at 16:23
  • 2
    You may have a look at this other SO question Commented Feb 7, 2020 at 16:27
  • If you want x1.var = ... to change a class attribute, you'll need to define a setter that explicitly sets the class attribute. Commented Feb 7, 2020 at 16:30

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

This will not change any var already set x2.var = 10 would not be overwritten by x1.__class__.var = 4
Good to know, thanks @Igoranze

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.