Python线程覆盖init

时间:2012-11-02 00:55:32

标签: python multithreading class inheritance initialization

我正在使用threading.py,我有以下代码:

import threading  
class MyClass(threading.Thread):  
    def __init__(self,par1,par2):
       threading.Thread.__init__(self)  
       self.var1 = par1  
       self.var2 = par2  
    def run(self):
       #do stuff with var1 and var2 while conditions are met
... 
... 
... 
myClassVar = MyClass("something",0.0)

我收到以下错误:

18:48:08    57  S E myClassVar = MyClass("something",0.0)  
18:48:08    58  S E File "C:\Python24\Lib\threading.py", line 378, in `__init__`  
18:48:08    59  S E assert group is None, "group argument must be None for now"  
18:48:08    60  S E AssertionError: group argument must be None for now  

我是使用python的新手,这是我第一次使用线程...

这里的错误是什么?

谢谢,

乔纳森

2 个答案:

答案 0 :(得分:7)

您不必扩展Thread来使用线程。我通常使用这种模式...

def worker(par1, par2):
    pass # do something

thread = threading.Thread(target=worker, args=("something", 0.0))
thread.start()

答案 1 :(得分:2)

您也可以像在示例中一样使用类和覆盖线程,只需将调用更改为super即可。例如:

import threading  
class MyClass(threading.Thread):  
    def __init__(self,par1,par2):
       super(MyClass, self).__init__()
       self.var1 = par1  
       self.var2 = par2  
    def run(self):
       #do stuff with var1 and var2 while conditions are met

对init的调用已经自动发送给它,所以当你再次提供它时,它会在Thread类构造函数中设置另一个参数,并且事情会变得混乱。