python __iter()__将迭代委托给内部对象操作
作者:
孙广宁 | 来源:发表于
2022-05-14 22:53 被阅读0次4.2 如果我们构建了一个容器对象,里边包含了,列表、元组、或者其它的可迭代对象,如何操作我们自己构建的这个对象
- 需要在对象内部构建一个iter()方法,将迭代请求委托给对象内部的迭代方法处理
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)
本文标题:python __iter()__将迭代委托给内部对象操作
本文链接:https://www.haomeiwen.com/subject/mvfwyrtx.html
网友评论