python __iter()__将迭代委托给内部对象操作

2022-05-14  本文已影响0人  孙广宁
4.2 如果我们构建了一个容器对象,里边包含了,列表、元组、或者其它的可迭代对象,如何操作我们自己构建的这个对象
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)

if __name__ == '__main__':
    root = Node(0)
    child1 = Node(1)
    child2 = Node(2)
    root.add_child(child1)
    root.add_child(child2)
    for ch in root:
        print(ch)
Adolph$ python test.py
Node(1)
Node(2)
上一篇 下一篇

猜你喜欢

热点阅读