一.实现Node迭代
构建了一个自定义容器Node对象,里面包含有列表、元组或其他可迭代对象,可以通过定义一个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)
def depth_first(self):
yield self
for c in self:
yield from c.depth_first()
if __name__ == "__main__":
root = Node(0)
child1 = Node(1)
child2 = Node(2)
root.add_child(child1)
root.add_child(child2)
child1.add_child(Node(3))
child1.add_child(Node(4))
child2.add_child(Node(5))
for ch in root.depth_first():
print(ch)
result如下:
Node(0)
Node(1)
Node(3)
Node(4)
Node(2)
Node(5)
Process finished with exit code 0
总结:Python 的迭代协议要求一个 iter () 方法返回一个特殊的迭代器对象,这个迭代器对象实现了 next () 方法并通过 StopIteration 异常标识迭代的完成.
二.反向迭代
可以通过在自定义类上实现迭代.如下:
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
n = self.start
while n > 0:
yield n
n -= 1
def __reversed__(self):
n = 1
while n <= self.start:
yield n
n += 1
def use_count():
for val in reversed(Countdown(10)):
print(val)
print("--------------")
for val in Countdown(10):
print(val)
if __name__ == "__main__":
use_count()
result如下:
1
2
3
4
5
6
7
8
9
10
--------------
10
9
8
7
6
5
4
3
2
1
Process finished with exit code 0
总结:定义一个反向迭代器可以使得代码非常的高效,因为它不再需要将数据填充到一个
列表中然后再去反向迭代这个列表