2012-02-25 146 views
4

我在這裏看到了一些關於我的錯誤的答案,但它對我沒有幫助。我是一個絕對的noob在Python上的類,並剛剛在9月份開始執行此代碼。反正看看我的代碼TypeError:__init __()只需要3個參數(給出2個參數)

class SimpleCounter(): 

    def __init__(self, startValue, firstValue): 
     firstValue = startValue 
     self.count = startValue 

    def click(self): 
     self.count += 1 

    def getCount(self): 
     return self.count 

    def __str__(self): 
     return 'The count is %d ' % (self.count) 

    def reset(self): 
     self.count += firstValue 

a = SimpleCounter(5) 

,這是錯誤我得到

Traceback (most recent call last): 
File "C:\Users\Bilal\Downloads\simplecounter.py", line 26, in <module> 
a = SimpleCounter(5) 
TypeError: __init__() takes exactly 3 arguments (2 given 
+2

據透露,你的類應該從'object'繼承(谷歌的蟒蛇新樣式類,如果你是好奇,爲什麼) – ThiefMaster 2012-02-25 14:54:56

回答

8

__init__()定義需要一個startValue一個firstValue。所以你必須通過這兩個(即a = SimpleCounter(5, 5))來使這個代碼工作。

不過,我得到的印象是工作在這裏的一些更深層次的困惑:

class SimpleCounter(): 

    def __init__(self, startValue, firstValue): 
     firstValue = startValue 
     self.count = startValue 

爲什麼你存儲startValuefirstValue,然後把它扔掉?在我看來,你錯誤地認爲__init__的參數自動成爲該類的屬性。事實並非如此。你必須明確地分配它們。因爲這兩個值都等於startValue,所以不需要將它傳遞給構造函數。你可以把它分配給self.firstValue像這樣:

class SimpleCounter(): 

    def __init__(self, startValue): 
     self.firstValue = startValue 
     self.count = startValue 
10

__init__()清晰的通話2個輸入值,startValuefirstValue。你只提供了一個值。

def __init__(self, startValue, firstValue): 

# Need another param for firstValue 
a = SimpleCounter(5) 

# Something like 
a = SimpleCounter(5, 5) 

現在,無論你真的需要2個值是不同的故事。 startValue僅用於設置firstValue值,所以你可以重新定義__init__()唯一一個使用方法:

# No need for startValue 
def __init__(self, firstValue): 
    self.count = firstValue 


a = SimpleCounter(5) 
相關問題