1

I have this bit of code:

class Car:
    wheels = 4


if __name__ == "__main__":
    car = Car()
    car2 = Car()
    print(car2.wheels)
    print(car.wheels)
    car.wheels = 3
    print(car.wheels)
    print(car2.wheels)

Which outputs:

4
4
3
4

Here "wheels" is defined as a class variable. Class variables are shared by all objects. However I can change its value for a SPECIFIC instance of that class?

Now I know to modify the class variable I need to use the class name:

Car.wheels = 3

I'm still confused as to how/why this happens. Am I creating an instance variable or am I overwriting the class variable for that instance using:

car.wheels = 3

-- Or something else?

Ry-
  • 218,210
  • 55
  • 464
  • 476
Simon
  • 107
  • 2
  • 10
  • 1
    Attributes are looked up first on the instance, then the class. So, when you set an attribute of the same name on an instance, it goes in the instance's `__dict__` and overrides the class attribute when looked up on that instance. – user2390182 Sep 27 '18 at 06:45
  • You might find this answer from [What is the difference between class and instance variables?](https://stackoverflow.com/a/8959269/8944057) helpful. – eugenhu Sep 27 '18 at 06:52

1 Answers1

1

You are right, you do not override the class attribute wheels, but create an instance attribute named wheels for the object car and set it to 3.

This can be verified using the special __dict__ attribute:

>>> class Car:
...   wheels=4
... 
>>> c1 = Car() 
>>> c2 = Car()
>>> 
>>> c1.wheels=3
>>> c1.wheels
3
>>> c2.wheels
4
>>> c1.__dict__
{'wheels': 3}
>>> c2.__dict__
{}
kalehmann
  • 4,821
  • 6
  • 26
  • 36