2016-12-02 95 views
1

我讀的地方,「如果蟒蛇找不到實例變量,它會嘗試返回具有相同名稱的類變量的值」類變量有不同的值不同的情況下

class Sample: 
    pi = 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 :(

發生了什麼?

+4

'pi'甚至沒有在你的課堂上定義過 – lmiguelvargasf

+0

對不起,關於錯字@lmiguelvargasf,我編輯帖子 –

回答

2

只要你分配到一個名稱上的一個實例,它獲得的是陰影類屬性的實例屬性。

您可以分配給類屬性的唯一方法是分配給類的屬性,而不是實例的屬性,例如,如果你有一個實例,你需要做的:

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來做到這一點)。

+0

注意:這個答案假設class屬性真的名爲'pi';你的例子命名爲'x',然後訪問'pi'。 – ShadowRanger