【问题标题】:Why can I override a class variable? Pointer being overridden? [duplicate]为什么我可以覆盖类变量?指针被覆盖? [复制]
【发布时间】: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

-- 还是别的什么?

【问题讨论】:

标签: python python-3.x variables instance-variables class-variables


【解决方案1】:

你是对的,你没有覆盖类属性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__
{}

【讨论】:

    猜你喜欢
    • 2019-07-26
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 2020-03-06
    • 1970-01-01
    • 2015-12-23
    相关资源
    最近更新 更多