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 看一下執行流程python

相關文章
相關標籤/搜索