Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't super(Thread, self).__init__() work for a threading.Thread subclass?

Every object I know of in Python can take care of its base class initialization by calling:

super(BaseClass, self).__init__()

This doesn't seem to be the case with a subclass of threading.Thread, since if I try this in SubClass.__init__(), I get:

RuntimeError: thread.__init__() not called

What gives this error? I looked at the source for threading.Thread and it looks like that __init__ method should set Thread.__initialized = True. I see that all examples use the following __init__:

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

But why?

like image 737
Carl G Avatar asked Feb 04 '10 05:02

Carl G


People also ask

What is INIT in thread?

__init__() method is called when an object is initialized. And when you do - Thread. __init__(self) , it just just calling the parent class' __init__() method . Like said in comment you can remove it and the functionality should remain same. In your class the __init__() is completely redundant.

Which of the following methods of a thread class can be overridden in Python?

The Thread class represents an activity that is run in a separate thread of control. There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass. No other methods (except for the constructor) should be overridden in a subclass.

How do you restart a thread in Python?

Calling the start() function on a terminated thread will result in a RuntimeError indicating that threads can only be started once. Instead, to restart a thread in Python, you must create a new instance of the thread with the same configuration and then call the start() function.


1 Answers

This works fine:

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

I think your code's bug is that you're passing the base class, rather than the current class, to super -- i.e. you're calling super(threading.Thread, ..., and that's just wrong. Hard to say since you don't show your failing code, but that's what I infer obliquely from the language you're using!-)

like image 81
Alex Martelli Avatar answered Oct 20 '22 17:10

Alex Martelli