• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
李晓否
一个不应该编程的程序员
博客园    首页    新随笔    联系   管理    订阅  订阅
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的参数,这样简直太方便的,就是不太好理解。

posted on 2017-10-21 11:20  李晓否  阅读(348)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3