2014-11-02 51 views
0

這個例子是由John V. Guttag使用Python編寫的介紹計算&編程屬性錯誤,同時創造一流

class IntSet(object): 
     def _init_(self): 
       self.vals= [] 
     #Rest of the code is fine 

     def insert(self,x): 
       if not x in self.vals: 
        self.vals.append(x) 


s= IntSet() 
s.insert(3) 

我得到一個錯誤:

Traceback (most recent call last): 
    File "/Users/abhimanyuaryan/Python/Classes/main.py", line 43, in <module> 
    s.insert(3) 
    File "/Users/abhimanyuaryan/Python/Classes/main.py", line 13, in insert 
    if not e in self.vals: 
AttributeError: 'IntSet' object has no attribute 'vals' 

回答

0

__init__代替_init_

+0

oops謝謝你的幫助......你還可以告訴爲什麼對象在IntSet類中作爲參數傳遞嗎? – 2014-11-02 15:57:35

+3

@ codejam.tk這不是一個參數,這是一個超類。你有沒有試過閱讀https://docs.python.org/2/tutorial/classes.html或類似的? – jonrsharpe 2014-11-02 15:59:09

2

您的構造函數應該是__init__,每邊有兩個下劃線_。因爲你沒有找到Python的構造函數s= IntSet(),所以從來沒有創建self.vals變量。 Python類的所有「魔術方法」將具有相同的格式,每個邊上有兩個下劃線_,詳細爲here

0

對於初學者,您實際上並沒有重寫初始化程序(__init__),因爲您在每一側使用了單下劃線而不是雙下劃線,所以實際上只是創建了一個名爲「_init_」的附加方法。

因此,當您運行代碼時,您使用默認對象初始值設定項實例化IntSet。 只需將_init_更改爲__init__即可。

E.G.

class IntSet(object): 
    def __init__(self): 
    self.vals = [] 
    . 
    . 
    . 
    (rest of code)