只要你分配到一个名称上的一个实例,它获得的是阴影类属性的实例属性。
您可以分配给类属性的唯一方法是分配给类的属性,而不是实例的属性,例如,如果你有一个实例,你需要做的:
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
,如果你想同类型x1
的所有实例显示更改。这从__class__
(或通过type
函数)获得类本身,然后分配给它。
如果你不小心创建一个实例属性,并希望再次露出class属性,你可以这样做:
del x1.pi
这会成功,如果一个实例属性命名pi
存在,raise AttributeError
如果它不(它将不会删除类属性,如果它存在,你需要做del x1.__class__.pi
/del type(x1).pi
来做到这一点)。
'pi'甚至没有在你的课堂上定义过 – lmiguelvargasf
对不起,关于错字@lmiguelvargasf,我编辑帖子 –