2010-07-09 24 views
0

我遇到了Python在訪問變量時拋出AttributeError的問題。使用成員變量的Python AttributeError

代碼如下,爲了清晰起見進行了編輯。

class mycollection(object): 
    """ 
    Collection of stuff. 
    """ 
    #"compile-time" define class variables. 
    __slots__ = ["stuff_list"] 

    def __init__(self): 
     self.stuff_list = [] 

    def add_stuff(self, stuff): 
     self.stuff_list.append(stuff) 


#later on.. 
collection = mycollection() 
stuff = stuff() 
collection.add_stuff(stuff) 

生成此錯誤。

Traceback (most recent call last): 
    File "", line 210, in <module> 
    main() 
    File "", line 206, in main 
    thestuff = load_file(inputfile, filetype) 
    File "pyyft.py", line 121, in load_file 
    collection.add_stuff(stuff) 
    File "pyyft.py", line 55, in add_test 
    self.stuff_list.append(stuff) 
AttributeError: stuff_list 

通過documentation檢查,我不明白爲什麼這個錯誤出現。

+3

某處在你的代碼,你必須(ERR,可能)有字符串 「test_stuff」。請發佈該代碼。 – unutbu 2010-07-09 17:45:41

+0

修復了'__init__'中的拼寫錯誤 - 如果您複製/粘貼了該文件,您可能需要在源代碼中修復它。另外,你使用'__slots__'的任何特定原因? – 2010-07-09 17:47:02

+0

@Jed - 是的,我正在避免自動版本 – 2010-07-09 17:49:41

回答

2

__ini__應該__init__

+0

評論應該是評論 – SilentGhost 2010-07-09 17:50:01

+0

Durp。當定時器OK時,接受傳入。 – 2010-07-09 17:50:09

+0

我看到傑德史密斯編輯了這個問題,但我懷疑這是原因。 – Oddthinking 2010-07-09 17:50:44

0

這是不是可以 「更Python」?

collection.stuff_list.append(test_stuff)

+0

僅僅因爲可以,與物體的內部狀態混雜在一起並不是Pythonic。 – 2010-07-09 18:13:52

+0

我並沒有把握'pythonic'這個概念的全部內容,但我確實知道你所建議的是在對象和對象所處的範圍之間泄露信息。換句話說,它增加了模塊之間的代碼耦合。換句話說,它打破了OO範式。然而,你稱之爲代碼維護和進化變得更加困難。 – 2010-07-09 19:35:46