Chinaunix首页 | 论坛 | 博客
  • 博客访问: 14552
  • 博文数量: 4
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 50
  • 用 户 组: 普通用户
  • 注册时间: 2014-10-16 20:05
文章分类
文章存档

2014年(4)

我的朋友

分类: Python/Ruby

2014-11-02 16:20:11


点击(此处)折叠或打开

  1. # the examples of yield and yield from syntax

  2. def accumulate():
  3.     tally = 0
  4.     print('accumulate before while')
  5.     while True:
  6.         print('accumulate before yield')
  7.         next = yield
  8.         print('accumulate after yield , next = {0}'.format(next))
  9.         if next is None:
  10.             return tally
  11.         tally += next

  12. def gather_tallies(tallies):
  13.     print('gather before while')
  14.     while True:
  15.         print('gather before yield')
  16.         tally = yield from accumulate()
  17.         print('gather after yield tally = {0}'.format(tally))
  18.         tallies.append(tally)

  19. tallies = []
  20. acc = gather_tallies(tallies)
  21. print('before next')
  22. next(acc)
  23. print('after next')
  24. print('before send')
  25. for i in range(4):
  26.     acc.send(i)
  27. print('after send')
  28. print('before send none')
  29. acc.send(None)
  30. print('after send none')

  31. for i in range(5):
  32.     acc.send(i)
  33. acc.send(None)
  34. print(tallies)
运行结果如下:

点击(此处)折叠或打开

  1. [Cambox@laptop ~]$ python34 python-test/test.py
  2. before next
  3. gather before while
  4. gather before yield
  5. accumulate before while
  6. accumulate before yield
  7. after next
  8. before send
  9. accumulate after yield , next = 0
  10. accumulate before yield
  11. accumulate after yield , next = 1
  12. accumulate before yield
  13. accumulate after yield , next = 2
  14. accumulate before yield
  15. accumulate after yield , next = 3
  16. accumulate before yield
  17. after send
  18. before send none
  19. accumulate after yield , next = None
  20. gather after yield tally = 6
  21. gather before yield
  22. accumulate before while
  23. accumulate before yield
  24. after send none
  25. accumulate after yield , next = 0
  26. accumulate before yield
  27. accumulate after yield , next = 1
  28. accumulate before yield
  29. accumulate after yield , next = 2
  30. accumulate before yield
  31. accumulate after yield , next = 3
  32. accumulate before yield
  33. accumulate after yield , next = 4
  34. accumulate before yield
  35. accumulate after yield , next = None
  36. gather after yield tally = 10
  37. gather before yield
  38. accumulate before while
  39. accumulate before yield
  40. [6, 10]


阅读(500) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~