2025-09-10:仓库迁移
This commit is contained in:
31
4.迭代器与生成器/4.迭代协议.py
Normal file
31
4.迭代器与生成器/4.迭代协议.py
Normal file
@@ -0,0 +1,31 @@
|
||||
# 这是标准的
|
||||
class Node:
|
||||
def __init__(self, value):
|
||||
self.value = value
|
||||
self._children = []
|
||||
|
||||
def __repr__(self):
|
||||
return "Node({})".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 child in self:
|
||||
yield from child.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))
|
||||
child2.add_child(Node(4))
|
||||
|
||||
for ch in root.depth_first():
|
||||
print(ch)
|
Reference in New Issue
Block a user