2017-04-10 52 views
0

我是新來的Python,看到這個代碼片段:del如何與對象屬性交互?

class C: 
    abc = 2 

c1 = C() 
print c1.abc 

c1.abc = 3 
print c1.abc 

del c1.abc 
print c1.abc 

我明白爲什麼第一和第二打印報表打印2,分別從3然而一個Java背景的人,我不明白是什麼發生在'del c1.abc'這一行,以及爲什麼最後的打印語句打印2而不是某種錯誤。有人可以解釋嗎?如果可能通過比較Java?

+0

@Aaron我不明白這與我的問題有甚麼關係。你能詳細說明嗎? – user6189

+2

這裏給Python初學者的一個棘手問題是'abc'是一個*類變量*(即一個「靜態」變量),當你做'c1.abc = 3'時,你*實例變量。當你做'del c1.abc'時,'del'適用於* instance *變量,因此現在調用'c1.abc'返回類變量。 –

+0

@Aaron但這不是這裏發生的事情。 –

回答

3

粘性問題在這裏一個Python初學者是abc是一個類變量(即「靜態」變量),當你這樣做c1.abc = 3,你影線的一個實例變量類變量。當你這樣做del c1.abcdel適用於實例變量,所以現在調用c1.abc返回類變量。

以下交互式會話應該清楚一些事情:

>>> class C: 
... abc = 2 
... 
>>> c1 = C() 
>>> c2 = C() 
>>> c1.abc = 3 
>>> c1.abc 
3 
>>> c2.abc 
2 
>>> C.abC# class "static" variable 
2 
>>> del c1.abc 
>>> c1.abc 
2 
>>> c2.abc 
2 
>>> C.abc 
2 
>>> del c2.abc 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: C instance has no attribute 'abc' 
>>> del C.abc 
>>> c1.abc 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: C instance has no attribute 'abc' 
>>> 

這是del.<someattribute>總是刪除實例屬性。如果應用於實例,它不會刪除類級屬性,而必須將其應用於類!

在Python中,所有寫在類塊中的東西都是,總是在類級別。從這個意義上講,它比Java更簡單。要定義一個實例變量,需要直接指定給實例,使用方法(c1.abc = 3)或方法內部,使用傳遞給該方法的第一個參數(通過約定,這稱爲self,但如果您想要,可以是 ):

>>> class C: 
... def some_method(banana, x): # by convention you should use `self` instead of `banana` 
...   banana.x = x 
... 
>>> c = C() 
>>> c.x 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: C instance has no attribute 'x' 
>>> c.some_method(5) 
>>> c.x 
5 
+0

非常感謝!這清除了很多東西! – user6189

+0

@ user6189我在Python中添加了一些關於類級別的變量。閱讀[官方教程](https://docs.python.org/3/tutorial/classes.html)很有幫助。 Python類的定義非常簡單,但它們的工作方式與Java類定義稍有不同。 –