Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python threading override init

I am using threading.py and I have the following code:

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)

And I get the following error:

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  

I am kind of new using python, it is the first time I use threading...

What is the bug here?

Thank you,

Jonathan

like image 749
JohnnyDH Avatar asked Jan 15 '23 03:01

JohnnyDH


2 Answers

You don't have to extend Thread to use threads. I usually use this pattern...

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

thread = threading.Thread(target=worker, args=("something", 0.0))
thread.start()
like image 90
FogleBird Avatar answered Jan 19 '23 00:01

FogleBird


You can also use a class and override thread as you have in your example, you just need to change the call to super to be correct. For example:

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

The call to init already gets self sent to it, so when you provide it again it sets another argument in the Thread class constructor and things get confused.

like image 44
Paul Wicks Avatar answered Jan 19 '23 00:01

Paul Wicks