I have some questions about inheriting thread class.
class MyThread(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self.num = num
def run(self):
print("Thread", self.num)
time.sleep(1)
why can't I only override the run method? The Python document of threading mention that "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."
Why does the above example code override the constructor also?
The constructor is overridden to pass the num
parameter from the place where instance of MyThread
is created to the run
method.
Note that you do not call run
method directly so you can't pass any parameters to it unless you store them in constructor.
If you don't need to pass parameters you can override only run
method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.