Your __init__ method is entirely redundant. You are in effect replacing Thread.__init__() with your own implementation, where your own implementation simply calls Thread.__init__(). If you removed it, nothing would change:
class Example(Thread):
def run (self):
print("It works!")
Your Example.run() method is simply called because you started the thread using the Thread.start() method:
start()
Start the thread’s activity.It must be called at most once per thread object. It arranges for the object’s
run()method to be invoked in a separate thread of control.
Also see the Thread.run() documentation:
run()
Method representing the thread’s activity.You may override this method in a subclass. The standard
run()method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
Your __init__ method had nothing to do with that.
Now, if you created a __init__ method in a Thread subclass and then did not make sure Thread.__init__ was called, then you prevented the class from setting important instance information, breaking instances:
>>> from threading import Thread
>>> class Example(Thread):
... def run (self):
... print("It works!")
...
>>> Example().start()
It works!
>>> class BrokenExample(Thread):
... def __init__(self):
... # not doing anything
... pass
... def run (self):
... print("It works!")
...
>>> BrokenExample().start()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/.../lib/python2.7/threading.py", line 737, in start
raise RuntimeError("thread.__init__() not called")
RuntimeError: thread.__init__() not called
Because this is a common error to make, the Thread.start method throws a custom exception to tell you explicitly that Thread.__init__ was not executed.
Your __init__ method is entirely redundant. You are in effect replacing Thread.__init__() with your own implementation, where your own implementation simply calls Thread.__init__(). If you removed it, nothing would change:
class Example(Thread):
def run (self):
print("It works!")
Your Example.run() method is simply called because you started the thread using the Thread.start() method:
start()
Start the thread’s activity.It must be called at most once per thread object. It arranges for the object’s
run()method to be invoked in a separate thread of control.
Also see the Thread.run() documentation:
run()
Method representing the thread’s activity.You may override this method in a subclass. The standard
run()method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
Your __init__ method had nothing to do with that.
Now, if you created a __init__ method in a Thread subclass and then did not make sure Thread.__init__ was called, then you prevented the class from setting important instance information, breaking instances:
>>> from threading import Thread
>>> class Example(Thread):
... def run (self):
... print("It works!")
...
>>> Example().start()
It works!
>>> class BrokenExample(Thread):
... def __init__(self):
... # not doing anything
... pass
... def run (self):
... print("It works!")
...
>>> BrokenExample().start()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/.../lib/python2.7/threading.py", line 737, in start
raise RuntimeError("thread.__init__() not called")
RuntimeError: thread.__init__() not called
Because this is a common error to make, the Thread.start method throws a custom exception to tell you explicitly that Thread.__init__ was not executed.
__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.
This method is called when you do -
Example()
When you create the new object for Example() .
The run() method is called, when you do - .start() on the Example() object. This is done by the Thread.start() method, from documentation -
start()
Start the thread’s activity.
It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.
Adding one more print statement and dividing Example().start() into two lines so you can understand this clearly -
>>> from threading import Thread
>>> class Example(Thread):
... def __init__(self):
... Thread.__init__(self)
... print("In __init__")
... def run (self):
... print("It's working!")
...
>>> e = Example()
In __init__
>>> e.start()
It's working!
>>> master_thread.start()
RuntimeError: thread.__init__() not called
Make sure to call Thread.__init__() in your Master.__init__:
class Master(Thread):
def __init__(self, dirlist):
super(Master, self).__init__()
self.dirlist = dirlist
Well i know it's late to answer but, what the hell, i am a newbie in python but this same thing was happening to me, so i went back to read the python tutorial and it has some differences with what we both we're trying, hope it helps. instead of this
import threading
class Master(Thread):
def set(self, dirlist):
self.dirlist = dirlist
def run(self):
observers = {}
for d in dirlist:
...
class according to the python tutorial:
class Master(threading.Thread):
this line is missing:
threading.Thread.__init__(self)
so it will end up being:
import threading
class Master(threading.Thread):
def __init__(self, dirlist):
threading.Thread.__init__(self)
self.dirlist = dirlist
def run(self):
observers = {}
for d in dirlist:
...
and that should work, at least work for me. I hope it was helpfull.
And your second try using the set method works, because you are not overriding the
__init__method
from Thread therefore the original init method from the parent class is used it runs as it's supposed.
Consider this simplified example:
class dog:
def __init__(self):
self.legs = 4
self.sound = 'woof'
class chihuahua(dog):
def __init__(self):
self.sound = 'yip'
# what's missing here?
We've created a subclass of dog, called chihuahua. A user of this class would reasonably expect it to behave like a dog in all default aspects, except the specific one that we have overridden (the sound it makes). But note that, as you have pointed out, the new subclass __init__ replaces the base class __init__. Completely replaces. Unlike C++, the base-class initialization code is not automatically called when a subclass instance is created. Therefore, the line self.legs = 4 never gets run when you create a chihuahua(). As a result, this type of dog is running around without any idea how many legs it has. Hence you could argue it is not a fully-functioning dog, and you shouldn't be surprised if it falls over while trying to perform complex tricks.
As subclass designer you have two options to fix this. The first is to reimplement the self.legs = 4 line explicitly in the subclass. Well, that'll work fine in this example, but it's not a great option in general because it violates the DRY principle even in cases where you do know exactly what code to write and how to maintain it. And in more complex examples (like your Thread subclass), you presumably won't know. Second option: explicitly call the superclass initializer and let it do its thing.
Defining your own __init__ overrides the base class. But what about all the work the base __init__ does to make the thread runnable? All variables and state that it would normally create are missing. Unless you hack all of that in yourself (and why do that?) the thread is of course completely unrunnable.
Not all classes need an __init__ of course, but the vast majority do. Even for the ones that don't, calling __init__ is harmless - it just goes to object.__init__ and future-proofs the child class in the event an implementer decides an __init__ is useful after all.
You don't need to use a subclass of Thread to make this work - take a look at the simple example I'm posting below to see how:
from threading import Thread
from time import sleep
def threaded_function(arg):
for i in range(arg):
print("running")
sleep(1)
if __name__ == "__main__":
thread = Thread(target = threaded_function, args = (10, ))
thread.start()
thread.join()
print("thread finished...exiting")
Here I show how to use the threading module to create a thread which invokes a normal function as its target. You can see how I can pass whatever arguments I need to it in the thread constructor.
There are a few problems with your code:
def MyThread ( threading.thread ):
- You can't subclass with a function; only with a class
- If you were going to use a subclass you'd want threading.Thread, not threading.thread
If you really want to do this with only functions, you have two options:
With threading:
import threading
def MyThread1():
pass
def MyThread2():
pass
t1 = threading.Thread(target=MyThread1, args=[])
t2 = threading.Thread(target=MyThread2, args=[])
t1.start()
t2.start()
With _thread:
import _thread
def MyThread1():
pass
def MyThread2():
pass
_thread.start_new_thread(MyThread1, ())
_thread.start_new_thread(MyThread2, ())
Doc for _thread.start_new_thread