python - 类变量的行为

标签 python python-3.x python-2.7 class oop

>>> class a:
...     b=5
...     def __init__(self,x,y):
...             self.x=x
...             self.y=y
...
>>> p=a(5,6)
>>> q=a(5,6)
>>> a.b
5
>>> a.b+=1
>>> p.b
6
>>> q.b
6
>>> q.b-=1
>>> q.b
5
>>> p.b
6
>>> a.b
6

如您所见,通过实例的方法更改类变量时,类变量和其他实例的类变量不会反射(reflect)相同的情况。为什么会这样?

最佳答案

因为 q.b -= 1 创建了一个名为 b 的实例变量,请查看您的 __dict__:

q.__dict__
{'b': 4, 'x': 5, 'y': 6}

p.__dict__
{'x': 5, 'y': 6}

q.ba.b 不同,您在赋值后隐藏了 a.b。请注意,这不是 Python 3 特有的问题,Python 2 也有同样的行为。

这在 assignment statement section 中有明确说明语言引用:

Note: If the object is a class instance and the attribute reference occurs on both sides of the assignment operator, the RHS expression, a.x can access either an instance attribute or (if no instance attribute exists) a class attribute. The LHS target a.x is always set as an instance attribute, creating it if necessary. Thus, the two occurrences of a.x do not necessarily refer to the same attribute: if the RHS expression refers to a class attribute, the LHS creates a new instance attribute as the target of the assignment:

class Cls:
    x = 3             # class variable
inst = Cls()
inst.x = inst.x + 1   # writes inst.x as 4 leaving Cls.x as 3

This description does not necessarily apply to descriptor attributes, such as properties created with property().

关于python - 类变量的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47355672/

相关文章:

python - 为什么 float() 比 int() 快?

python-2.7 - 创建局部变量来表示 xpath tr[ ] 内的数字范围?

python - 我怎样才能用pyqt在qtableview中显示一个矩阵

python - 谷歌应用服务器 "unable to add testProject to attribute application"正则表达式问题中的 yaml 异常?

python - 在图像opencv上画一个圆圈

Powershell 中的 Python 2 和 3

python-3.x - cython 编译 - 导入与 cimport

python - 如何检查当前tensorflow版本是否至少是python脚本中的特定版本?

python - 禁止在 Python 中访问 exec 和 eval 中的文件系统

python - 在固定时间间隔后查找最后一个可用时间戳 - pandas 或 numpy