Why can I change class attributes for an instance without changing the class value in Python?

Viewed 1440

In Java, there's no way to change a static variable (what I thought was more or less the same as a Python class attribute) for just an instance.

In Python, however, I tried the following code in an interactive session:

>>> class TestClass:
...    x = 0
...
>>> a = TestClass()
>>> a.x += 1
>>> a.x 
1
>>> TestClass.x 
0
>>> TestClass.x = 2
>>> a.x 
1
>>> TestClass.x 
2

Further, I checked the IDs of both a.x and TestClass.x and determined that they weren't equal, so I guessed that there's an instance-level x and a class-level x. Can anyone explain why this is?

I figure the best way to modify a class attribute through an instance through a method that modifies TestClass.x, but I also can't figure out quite why this behavior exists as is.

1 Answers

Basically, when looking up a variable, python will first look at the instance level to see if the variable exists there, and then at the class level. When you do

a.x += 1

What's happening is that it's setting a.x to the class level x variable plus 1.

And later on when you do a.x, it's looking to see if x is available at the instance level (and it is), and so it's using that value.

But if you did b = TestClass() and then b.x without setting x on the instance level, then python would look up x on the instance level (does not exist), and then on the class level (does exist), and use that value

Related