每天CookBook之Python-058

  • 使对象支持迭代器

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)
    child3 = Node(3)
    root.add_child(child1)
    root.add_child(child2)
    root.add_child(child3)
    for ch in root:
        print(ch)

out

Node(1)
Node(2)
Node(3) 
posted @ 2016-07-21 23:12  4Thing  阅读(109)  评论(0编辑  收藏  举报