我有这段代码:
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
--或者其他什么?
最佳答案
你是对的,你没有重写类属性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__
{}
关于python - 为什么我可以覆盖类变量?指针被覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52530787/