【求教】这段书上的代码,删掉def __call__(self): 会有什么后果
python吧
全部回复
仅看楼主
level 5
gin741 楼主
删掉后会报
self._target(*self._args, **self._kwargs)
TypeError: 'ThreadFunc' object is not callable
代码如下
import threading
from time import sleep,ctime
loops=[4,2]
class ThreadFunc:
def __init__(self,func,args,name=''):
self.func=func
self.args=args
self.name=name
def __call__(self):
self.func(*self.args)
def loop(nloop,nsec):
print('start loop',nloop,'at:',ctime())
sleep(nsec)
print("loop",nloop,'done at:',ctime())
def main():
print('starting at:',ctime())
threads=[]
nloops=range(len(loops))
for i in nloops:
t=threading.Thread(target=ThreadFunc(loop,(i,loops[i]),loop.__name__))
threads.append(t)
for i in nloops:
threads[i].start()
for i in nloops:
threads[i].join()
print ('ALL DONE AT:',ctime())
if __name__=='__main__':
main()
2016年11月19日 16点11分 1
level 5
gin741 楼主
这句话作用是什么
2016年11月19日 16点11分 2
level 13
线程对象应该是可以调用的,比如function。__call__方法允许把类对象当做一个方法调用
2016年11月20日 02点11分 3
level 1
老哥,你敲出这段代码能运行吗,我这里一直在loop_name_上报错
2019年01月03日 14点01分 4
1