1.关于__call__的很有意思的用法

 1 #!/usr/bin/env python
 2 
 3 import threading
 4 from time import sleep, ctime
 5 
 6 loops = [4, 2]
 7 
 8 class ThreadFunc(object):
 9     def __init__(self, func, args, name=''):
10         self.name = name
11         self.func = func
12         self.args = args
13 
14     def __call__(self):
15         self.func(*self.args)
16 
17 def loop(nloop, nsec):
18     print 'start loop', nloop, 'at:', ctime()
19     sleep(nsec)
20     print 'loop', nloop, 'done at:', ctime()
21 
22 def main():
23     print 'starting at:', ctime()
24     threads = []
25     nloops = range(len(loops))
26 
27     for i in nloops:        # create all threads
28         t = threading.Thread(
29             target=ThreadFunc(loop, (i, loops[i]),
30             loop.__name__))
31         threads.append(t)
32 
33     for i in nloops:        # start all threads
34         threads[i].start()
35 
36     for i in nloops:        # wait for completion
37         threads[i].join()
38 
39     print 'all DONE at:', ctime()
40 
41 if __name__ == '__main__':
42     main()

以上就是这次要说的代码。

这是一个使用Threading来进行多线程测试的代码。

其中最有意思的是对__call__方法的使用。

它起到的目的是,因为在Threadfunc类中已经传入的arg函数,这是一个元组,从下边的调用可以看出来。

__call__的作用是重写了之后可以让一个类当做函数使用,本来类后边加()只是单纯的实例化,但是你修改了这个魔法方法后,可以同时执行一个类似函数的作用,它所执行的函数操作就是__call__里所定义的。

所以第29行的作用就是,实例化一个类的同时,又调用了传入的func函数(也就是loop),又使用传入的参数args当做func的参数,这样简直太方便的,就是不太好理解。

原文地址:https://www.cnblogs.com/lixiaofou/p/7704193.html