"""
自定义线程类
"""
from threading import Thread
from time import sleep, ctime
class MyThread(Thread):
def __init__(self, target=None, args=(), kwargs={}):
super().__init__()
self.target = target
self.args = args
self.kwargs = kwargs
def run(self):
self.target(*self.args, **self.kwargs)
def player(song, sec):
for i in range(3):
sleep(sec)
print('Playing %s : %s' % (song, ctime()))
t = MyThread(target=player, args=('葫芦娃', 2))
t.start()
t.join()
运行结果:
Playing 葫芦娃 : Mon Oct 4 13:41:06 2021 Playing 葫芦娃 : Mon Oct 4 13:41:08 2021 Playing 葫芦娃 : Mon Oct 4 13:41:10 2021 Process finished with exit code 0
ps 自定义进程、线程类的用途:当我们封装的时候 一个函数并不满足我们的封装要求时 可以使用类 更符合面向对象编程思想



