Files
python3-cookbook/cookbook/c04/p02_delegate_iter.py
2014-09-14 18:47:29 +08:00

33 lines
609 B
Python

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: 代理迭代
Desc :
"""
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)
# Example
if __name__ == '__main__':
root = Node(0)
child1 = Node(1)
child2 = Node(2)
root.add_child(child1)
root.add_child(child2)
# Outputs Node(1), Node(2)
for ch in root:
print(ch)