Files
2025-09-10 16:12:45 +08:00

29 lines
764 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

if __name__ == "__main__":
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)
# 对象的内置iter方法在迭代对象的时候将迭代请求转发返回children的迭代器对象
# iter函数和len函数一样底层原理都是返回对象的底层方法iter返回对象的__iter__()
def __iter__(self):
return iter(self._children)
root = Node(0)
child1 = Node(1)
child2 = Node(2)
root.add_child(child1)
root.add_child(child2)
for ch in root:
print(ch)