- 阅读权限
- 255
- 威望
- 1 级
- 论坛币
- 49640 个
- 通用积分
- 55.8137
- 学术水平
- 370 点
- 热心指数
- 273 点
- 信用等级
- 335 点
- 经验
- 57805 点
- 帖子
- 4005
- 精华
- 21
- 在线时间
- 582 小时
- 注册时间
- 2005-5-8
- 最后登录
- 2023-11-26
|
- 4.2. Delegating Iteration
- Problem
- You have built a custom container object that internally holds a list, tuple, or some other
- iterable. You would like to make iteration work with your new container.
- Solution
- Typically, all you need to do is define an __iter__() method that delegates iteration to
- the internally held container. For example:
- 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)
- for ch in root:
- print(ch)
- # Outputs Node(1), Node(2)
复制代码
|
|