2011-03-22 57 views
0

我有這樣初始化數據的屬性

class SomeClass: 
    def doSomething(self): 
     self.counter = 50 

我創建一個實例xSomeClass

x = SomeClass() 

類當我嘗試獲取計數器的值是這樣的:x.counter我得到的以下錯誤 -

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: SomeClass instance has no attribute 'counter' 

但是在我調用成員函數x.doSomething()然後查找數據屬性,它是可用的。

>>> x.doSomething() 
>>> x.counter 
50 

這是爲什麼?一旦創建實例,是否所有數據屬性都不可用?

謝謝。

回答

7

否,self.counter僅在創建時調用doSomething()。在Python中,實例屬性是動態的,可以在運行時創建。若要從創建對象的self.counter,把它的初始化在構造函數中:

class SomeClass: 
    def __init__(self): 
     self.counter = None 
    def doSomething(self): 
     self.counter = 50 

現在的SomeClass所有實例都提供從開始self.counter,雖然它的價值將是None直到doSomething被調用。自然,這個主題有很多變種,可以讓你實現你感興趣的確切語義。

+0

謝謝。遵循這個建議的做法是什麼?或者我們應該初始化'__init__'中的所有數據屬性? – bdhar 2011-03-22 08:21:21

+0

看起來像你修改了我在之前的評論中回答我的問題的答案。謝謝。 – bdhar 2011-03-22 08:22:24

+1

@bdhar:除非你做了一些特別的事情,否則我會建議讓所有實例屬性在構造函數中初始化。 – 2011-03-22 08:22:38