python - 为什么我可以覆盖类变量?指针被覆盖?

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

我有这段代码:

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/

相关文章:

python - Tkinter columnconfigure 重量不调整

python - 如何自动创建变量?

variables - 无法获取继承的 gitlab CI/CD 变量

python - 与串行运行相比,在双核 CPU 上并行运行两个脚本是否会降低速度?

python - 构建正则表达式来检测字典

python - 定义在初始化时按顺序计算属性的类的最佳实践

python-3.x - 带有 for 循环的多处理池

python - 使用Python Pysftp连接SFTP服务器时出错

python - 如何在Python中根据某些条件剪切字符串的末尾?

ios - swift 中的相同数据类型多变量声明