zoukankan      html  css  js  c++  java
  • 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"
    ')], maxlen=3) 21 deque([(1, '"hello"
    '), (2, '  你好 python
    ')], 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"
    ')], maxlen=3)
    deque([(1, '"hello"
    '), (2, '  你好 python
    ')], maxlen=3)
    1:"hello"
    2:  你好 python
    deque([(1, '"hello"
    '), (2, '  你好 python
    '), (3, '萨瓦迪卡
    ')], maxlen=3)
    """
    
    # 总结: 在 __iter__() 方法中定义你的生成器不会改变你任何的算法逻辑。 由于它是类的一部分,所以允许你定义各种属性和方法来供用户使用

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

  • 相关阅读:
    Python之异常篇 [待更新]
    python脚本工具 - 4 获取系统当前时间
    python脚本工具 - 3 目录遍历
    数字签名和数字证书到底是个神马玩意?
    CSRF攻击[转]
    Python之数据结构篇
    Python之模块篇
    Python之函数篇
    python脚本工具-2 去除扩展名后提取目录下所有文件名并保存
    python脚本工具-1 制作爬虫下载网页图片
  • 原文地址:https://www.cnblogs.com/zzy-9318/p/10491255.html
Copyright © 2011-2022 走看看