Search code examples
pythonpython-3.xvariablesinstance-variablesclass-variables

Why can I override a class variable? Pointer being overridden?


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?


Solution

  • 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__
    {}