Python学习笔记之:threading.Thread 类的继承和改造


开启一个线程的基本方法:

1. 开启新线程的基本原理

new_thread =  threading.Thread(target=, args= )  # 创建一个线程 
new_thread. start() 			# 启动这个线程

即先创建一个线程,然后使用 start 方法来启动这个线程

那么为什么要用start()方法来开始线程呢,其实其更底层原理是:

在这里插入图片描述

文中框起来的意思是:每个线程对象最多只能调用一次。 它安排在单独的控制线程中调用对象的run()方法。如果在同一线程对象上多次调用此方法,则会引发RuntimeError。

也就是说,start() 方法其实最底层是调用了 run() 方法来执行 “开启线程” 操作的;所以 如果我们要继承并重写线程,应该对 run() 方法进行修改

2. 继承并重写 threading.Thread 类

2.1 重写 threading.Thread 类中的对象方法

上面提到了,要重写方法的话应该重写 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() 方法即可

2.2 重写 threading.Thread 类中的对象属性

与其他类的继承和重写对象属性一样,需要先使用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__ 的操作,结果如下:
在这里插入图片描述

3. 总结:

  • 继承和重写 threading.Thread() 类中的对象方法,可以通过改造 run() 方法实现
  • 重写对象属性要先通过 super()._init_ 方法继承父类的 对象属性,然后进行重写改造
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

暖仔会飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值