Python之带有外部状态的生成器函数

带有外部状态的生成器函数,也就是你的生成器暴露外部状态给用户
解决:
 定义一个类,然后把生成器函数放到 __iter__() 方法中过去
 定义一个类,然后把生成器函数放到 __iter__() 方法中过去
from collections import deque

class Linehistory:  # 4
    def __init__(self,lines,histry=3):   # 1 7
        self.lines=lines  # 8
        self.history=deque(maxlen=histry)  # 9

    def __iter__(self):   #   # 2  12
        print("111")  # 13
        for lineno,line in enumerate(self.lines,1):  # 14 19 30  37
            self.history.append((lineno,line))  # 15 20 31
            print(self.history)   # 16 deque([(1, '"hello"\n')], maxlen=3) 21 deque([(1, '"hello"\n'), (2, '  你好 python\n')], maxlen=3)  32
            yield line   # 18 循环会挂起29  33  36

    def clear(self):  # 3
        self.history.clear()

# testData
"""
"hello"
  你好 python
萨瓦迪卡
"""
with open("../../testData") as f:  # 5
    lines = Linehistory(f)   # 的迭代对象  # 6  10
    for line in lines:  # 11 28 35  for循环会调用__iter__方法
        if 'python' in line:  # 17  22  34
            for lineno, hline in lines.history:  # 23 26
                print('{}:{}'.format(lineno, hline), end='')  # 25 1:"hello" 27 2:  你好 python

"""
111
deque([(1, '"hello"\n')], maxlen=3)
deque([(1, '"hello"\n'), (2, '  你好 python\n')], maxlen=3)
1:"hello"
2:  你好 python
deque([(1, '"hello"\n'), (2, '  你好 python\n'), (3, '萨瓦迪卡\n')], maxlen=3)
"""

# 总结: 在 __iter__() 方法中定义你的生成器不会改变你任何的算法逻辑。 由于它是类的一部分,所以允许你定义各种属性和方法来供用户使用

感兴趣或者不太明白的可以粘贴代码,在pycharm 中,debug 看一下执行流程

posted on 2019-03-07 17:54  V神丫丫  阅读(334)  评论(0编辑  收藏  举报