【发布时间】:2019-03-03 00:03:42
【问题描述】:
我有这段代码:
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
-- 还是别的什么?
【问题讨论】:
-
属性首先在实例上查找,然后是类。因此,当您在实例上设置同名属性时,它会进入实例的
__dict__并在查找该实例时覆盖类属性。 -
您可能会发现来自What is the difference between class and instance variables? 的这个答案很有帮助。
标签: python python-3.x variables instance-variables class-variables