首页 > 解决方案 > 为什么我可以覆盖类变量?指针被覆盖?

问题描述

我有这段代码:

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”被定义为一个类变量。类变量由所有对象共享。但是我可以为该类的特定实例更改它的值吗?

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

Car.wheels = 3

我仍然对如何/为什么会发生这种情况感到困惑。我是在创建实例变量还是使用以下方法覆盖该实例的类变量:

car.wheels = 3

- 或者是其他东西?

标签: pythonpython-3.xvariablesinstance-variablesclass-variables

解决方案


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

这可以使用特殊__dict__属性进行验证:

>>> class Car:
...   wheels=4
... 
>>> c1 = Car() 
>>> c2 = Car()
>>> 
>>> c1.wheels=3
>>> c1.wheels
3
>>> c2.wheels
4
>>> c1.__dict__
{'wheels': 3}
>>> c2.__dict__
{}

推荐阅读