2013-03-17 22 views
3

我試圖用表現爲an answer to another questionStoppableThread類:超類__init__不承認其kwargs

import threading 

# Technique for creating a thread that can be stopped safely 
# Posted by Bluebird75 on StackOverflow 
class StoppableThread(threading.Thread): 
    """Thread class with a stop() method. The thread itself has to check 
    regularly for the stopped() condition.""" 

    def __init__(self): 
     super(StoppableThread, self).__init__() 
     self._stop = threading.Event() 

    def stop(self): 
     self._stop.set() 

    def stopped(self): 
     return self._stop.isSet() 

但是,如果我用如下命令:

st = StoppableThread(target=func) 

我得到:

TypeError: __init__() got an unexpected keyword argument 'target'

可能是應該如何使用它的疏忽。

回答

5

StoppableThread類不會在構造函數中將任何其他參數傳遞給threading.Thread。你需要做這樣的事情:

class StoppableThread(threading.Thread): 
    """Thread class with a stop() method. The thread itself has to check 
    regularly for the stopped() condition.""" 

    def __init__(self,*args,**kwargs): 
     super(threading.Thread,self).__init__(*args,**kwargs) 
     self._stop = threading.Event() 

這將傳遞位置和關鍵字參數到基類。

1

你是壓倒性的初始和你的初始沒有任何參數。你應該添加一個「目標」參數,並將它傳遞給你的基類構造函數,超級甚至更好,通過* args和* kwargs允許任意參數。

I.e.

def __init__(self,*args,**kwargs): 
    super(threading.Thread,self).__init__(*args,**kwargs) 
    self._stop = threading.Event()