zoukankan      html  css  js  c++  java
  • 实现迭代器协议

    demo1

    class Node:
        def __init__(self, value):
            self._value = value
            self._children = []
    
        def __repr__(self):
            return 'Node({!r})'.format(self._value)
    
        def add_child(self, node):
            self._children.append(node)
    
        def __iter__(self):
            return iter(self._children)
    
        def depth_first(self):
            yield self
            for c in self:
                yield from c.depth_first()
    
    # Example
    if __name__ == '__main__':
        root = Node(0)
        child1 = Node(1)
        child2 = Node(2)
        root.add_child(child1)
        root.add_child(child2)
        child1.add_child(Node(3))
        child1.add_child(Node(4))
        child2.add_child(Node(5))
        child2.add_child(Node(6))
        for ch in root.depth_first():
            print(ch)
        # Outputs Node(0), Node(1), Node(3), Node(4), Node(2), Node(5)

    输出:

    Node(0)
    Node(1)
    Node(3)
    Node(4)
    Node(2)
    Node(5)
    Node(6)

    demo2

    class Node2:
        def __init__(self, value):
            self._value = value
            self._children = []
    
        def __repr__(self):
            return 'Node({!r})'.format(self._value)
    
        def add_child(self, node):
            self._children.append(node)
    
        def __iter__(self):
            return iter(self._children)
    
        def depth_first(self):
            return DepthFirstIterator(self)
    
    
    class DepthFirstIterator(object):
        '''
        Depth-first traversal
        '''
    
        def __init__(self, start_node):
            self._node = start_node
            self._children_iter = None
            self._child_iter = None
    
        def __iter__(self):
            return self
    
        def __next__(self):
            # Return myself if just started; create an iterator for children
            if self._children_iter is None:
                self._children_iter = iter(self._node)
                return self._node
            # If processing a child, return its next item
            elif self._child_iter:
                try:
                    nextchild = next(self._child_iter)
                    return nextchild
                except StopIteration:
                    self._child_iter = None
                    return next(self)
            # Advance to the next child and start its iteration
            else:
                self._child_iter = next(self._children_iter).depth_first()
                return next(self)

  • 相关阅读:
    STM32-使用软件模拟I2C读写外部EEPROM(AT24C02)
    STM32-软件模拟I2C
    STM32_使用DAC输出三角波
    VS常用快捷键
    C语言volatile关键字在单片机中的作用
    如何使用数据库引擎优化顾问优化数据库(转)
    SQLServer数据库慢查询追踪
    怎么获取基金净值数据?(科普)
    解决了一个ssh登录缓慢的问题
    oracle存储过程转达梦8存储过程时踩过的坑2(完结篇)
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10566883.html
Copyright © 2011-2022 走看看