2009-10-23 35 views
8

我有這個類:什麼是導致「unbound method __init __()必須從此Python代碼中以實例作爲第一個參數調用?」

from threading import Thread 
import time 

class Timer(Thread): 
    def __init__(self, interval, function, *args, **kwargs): 
     Thread.__init__() 
     self.interval = interval 
     self.function = function 
     self.args = args 
     self.kwargs = kwargs 
     self.start() 

    def run(self): 
     time.sleep(self.interval) 
     return self.function(*self.args, **self.kwargs) 

和我有這個腳本調用它:

import timer 
    def hello(): 
     print \"hello, world 
    t = timer.Timer(1.0, hello) 
    t.run() 

,並得到這個錯誤,我想不通爲什麼:unbound method __init__() must be called with instance as first argument

回答

15

你正在做的:

Thread.__init__() 

用途:

Thread.__init__(self) 

或者說,用super()

+6

這將是超級(線程,自我).__ init __()' - 但超級也有它自己的問題:/ – 2009-10-23 18:35:27

+2

@ THC4k:超級沒有問題,多重繼承有問題。如果你使用多重繼承,那麼super比直接調用要好得多。 – nikow 2009-10-24 09:03:18

+0

super僅僅是一個災難的祕訣,特別是在多重繼承中,尤其是如果有任何需要重新加載的擴展。 – dashesy 2014-09-09 21:10:05

10

這是一個在SO上經常被問到的問題,但簡而言之,答案就是您稱爲超類構造函數的方式如下所示:

super(Timer,self).__init__() 
1

你只需要通過 '自我' 作爲參數「主題。 init'。之後,它在我的機器上運行。

1

首先,原因必須使用:

Thread.__init__(self) 

代替

Thread.__init__() 

是因爲你使用的是類名,而不是一個對象(類的實例),所以您不能以與對象相同的方式調用方法。

其次,如果你使用Python 3,從子類調用父類方法推薦的風格是:

super().method_name(parameters) 

雖然在Python 3可以使用:

SuperClassName.method_name(self, parameters) 

這是一種舊式的語法,不是喜歡的風格。

相關問題