python 实现迭代协议

2022-05-15  本文已影响0人  孙广宁
4.4 如何实现一个比4.2节简单的迭代方法
class Node:
    def __init__(self,value):
        self.value = value
        self._children =[]

    def __repr__(self):
        return 'Node({})'.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()

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))

    for ch in root.depth_first():
        print(ch)
上一篇 下一篇

猜你喜欢

热点阅读