为什么我可以覆盖 class 变量?指针被覆盖?

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

我有这段代码:

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)

输出:

4
4
3
4

这里"wheels"定义为一个class变量。 Class 变量由所有对象共享。但是我可以为 class?

的特定实例更改它的值

现在我知道要修改 class 变量我需要使用 class 名称:

Car.wheels = 3

我仍然对 how/why 这种情况感到困惑。我是在创建实例变量,还是在使用

覆盖该实例的 class 变量
car.wheels = 3

-- 还是别的?

你是对的,你没有覆盖 class 属性 wheels,而是为对象 car 创建一个名为 wheels 的实例属性并将其设置为 3 .

这可以使用 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__
{}