2010-02-04 231 views
15

我知道在Python可以通過調用照顧其基類的初始化的每個對象:爲什麼super(Thread,self).__ init __()爲threading.Thread子類工作?

super(BaseClass, self).__init__() 

這似乎並不符合的threading.Thread子類的情況下,因爲如果我嘗試這SubClass.__init__(),我得到:

RuntimeError: thread.__init__() not called 

是什麼給出了這個錯誤?我查看threading.Thread的來源,看起來__init__方法應該設置爲Thread.__initialized = True。我看到所有示例使用以下內容__init__

class YourThread(threading.Thread): 
    def __init__(self, *args): 
     threading.Thread.__init__(self) 
     # whatev else 

但是爲什麼?

回答

40

這工作得很好:

>>> class MyThread(threading.Thread): 
... def __init__(self): 
...  super(MyThread, self).__init__() 

我覺得你的代碼的錯誤是,你傳遞的基地類,而不是當前,以super - 即你打電話super(threading.Thread, ... ,那只是錯誤的。很難說,因爲你不顯示你失敗的代碼,但這就是我從你正在使用的語言傾斜推斷! - )

+0

我認爲你已經推斷正確 – 2010-02-04 06:29:53

+0

嗨,你是對的。衛生署!謝謝。 – 2010-02-08 06:18:10

+0

這是有見地的。 +1。 – 2013-05-30 11:07:19

相關問題