赞
踩
new_thread = threading.Thread(target=, args= ) # 创建一个线程
new_thread. start() # 启动这个线程
即先创建一个线程,然后使用 start 方法来启动这个线程
那么为什么要用start()方法来开始线程呢,其实其更底层原理是:
文中框起来的意思是:每个线程对象最多只能调用一次。 它安排在单独的控制线程中调用对象的run()方法。如果在同一线程对象上多次调用此方法,则会引发RuntimeError。
也就是说,start() 方法其实最底层是调用了 run() 方法来执行 “开启线程” 操作的;所以 如果我们要继承并重写线程,应该对 run() 方法进行修改
上面提到了,要重写方法的话应该重写 run() 方法,如下:
import threading
class MyThread(threading.Thread): # 继承父类
def run(self): # 重写run方法
for i in range(5):
print('i love running')
if __name__ == '__main__':
new_thread = MyThread() # 实例化对象
new_thread.start() # 开始新线程
只需要重新 run() 方法即可
与其他类的继承和重写对象属性一样,需要先使用super() 方法来继承父类的 _init_ 中的部分,然后再进行重写加以覆盖,如下:
import threading
class MyThread(threading.Thread):
def __init__(self,number):
super().__init__()
self.number = number
if __name__ == '__main__':
new_thread = MyThread(number=5)
new_thread.start()
print(new_thread.number)
如果缺少了
super().__init__
这个继承父类__init__
的操作,结果如下:
- 继承和重写 threading.Thread() 类中的对象方法,可以通过改造 run() 方法实现
- 重写对象属性要先通过 super()._init_ 方法继承父类的 对象属性,然后进行重写改造
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。