只要你分配到一個名稱上的一個實例,它獲得的是陰影類屬性的實例屬性。
您可以分配給類屬性的唯一方法是分配給類的屬性,而不是實例的屬性,例如,如果你有一個實例,你需要做的:
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,我編輯帖子 –