python - 为什么我可以覆盖类变量?指针被覆盖?
问题描述
我有这段代码:
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
,而是创建一个以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__
{}
推荐阅读
- c++ - 从文本文件c ++填充对象
- powershell - 有条件地将输出写入文件以跟踪 pourposes
- c# - Uri 方案太长 – AppSettings.config
- database - 从 Oracle 云存储读取数据到目标数据库
- c# - 如何查找 String 中是否有特殊字符?前任 : ” ] ”
- git - 我可以从不同的分支中挑选多个提交吗?
- apache-nifi - 如何使用 Apache Nifi 将数据从 HDFS 传输到 Oracle?
- angular - Angular:将类型字符串返回到 catchError 但具有不同类型的 HTTP
- reactjs - 可重用组件静态图像不会加载到不同的路由上
- node.js - 从 `prom-client` 模块导入 `prom` 丢失但已安装。我怎样才能相应地`import prom-client`?