Class variable have different values for different instances
本问题已经有最佳答案,请猛点这里访问。
我在某个地方读到,"如果python找不到实例变量,它将尝试返回具有相同名称的类变量的值。"
如
1 2 | class Sample: pi = 10 |
现在
1 2 3 4 5 6 7 8 9 10 | x1 = Sample() x2 = Sample() x1.pi # returns 10 x2.pi # returns 10 x1.pi = 20 # change the value of class variable x1.pi # return 20 (OK) x2.pi # still returns 10 :( Sample.pi # returns 10 :( |
发生什么事了??
一旦分配给实例上的名称,它就会获得一个实例属性,该属性会隐藏类属性。
唯一可以分配给类属性的方法是分配给类的属性,而不是实例的属性,例如,如果有实例,则需要执行以下操作:
1 2 3 4 5 6 | x1.__class__.pi = 20 # If you're on Py3, or on Py2 and x1 is an instance of a new-style class, # using type(x1) is slightly"nicer" than manually accessing dunder special # variables, but unfortunately, it doesn't work on old-style class instances # For new-style class instances though, the following is equivalent: type(x1).pi = 20 |
如果希望所有与
如果不小心创建了实例属性并希望再次公开类属性,则可以执行以下操作:
1 | del x1.pi |
如果存在名为