Class variable have different values for different instances
This question already has an answer here:
As soon as you assign to a name on an instance, it gains an instance attribute that shadows the class attribute.
The only way you can assign to the class attribute is to assign to an attribute of the class, not an attribute of the instance, eg if you have an instance, you need to do:
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
if you want all instances of the same type as x1
to show the change. This gets the class itself from __class__
(or via type
function), then assigns to it.
If you accidentally created an instance attribute and want to expose the class attribute again, you can do:
del x1.pi
which will succeed if an instance attribute named pi
exists, and raise AttributeError
if it does not (it will not delete the class attribute if it exists, you'd need to do del x1.__class__.pi
/ del type(x1).pi
to do that).
上一篇: python列表中的所有值都是相同的
下一篇: 类变量对于不同的实例具有不同的值