1、迭代器:可迭代对象、迭代器
class NodeIter:
def __init__(self, node) -> None:
self.cur_node = node
def __next__(self):
if self.cur_node == None:
raise StopIteration
node, self.cur_node = self.cur_node, self.cur_node.next
return node
def __iter__(self):
return self
class Node:
def __init__(self, name) -> None:
self.name = name
self.next = None
def __iter__(self):
return NodeIter(self)
node1 = Node('node1')
node2 = Node('node2')
node3 = Node('node3')
node1.next = node2
node2.next = node3
for node in node1:
print(node.name)
print('--------------------')
it = iter(node1)
first = next(it)
for node in it:
print(node.name)
2、生成器创建Node
class Node:
def __init__(self, name) -> None:
self.name = name
self.next = None
def __iter__(self):
node = self
while node is not None:
yield node
node = node.next
node1 = Node('node1')
node2 = Node('node2')
node3 = Node('node3')
node1.next = node2
node2.next = node3
for node in node1:
print(node.name)
print('--------------------')
it = iter(node1)
first = next(it)
for node in it:
print(node.name)
3、生成器
# 生成器函数
def gen(num):
while num > 0:
yield num
num -= 1
return None
# 生成器对象
g = gen(5)
for i in g:
print(i)
print('--------------------')
g = gen(5)
first = next(g)
for i in g:
print(i)
4、生成器Send
# %%
# 生成器函数
def gen(num):
while num > 0:
tmp = yield num
if tmp is not None:
num = tmp
num -= 1
return None
g = gen(5)
first = next(g)
print(f'first: {first}')
print(f'send: {g.send(10)}')
for i in g:
print(i)
print('-------------------')
g = gen(5)
first = next(g)
print(f'first: {first}')
print(f'send: {g.send(None)}')
for i in g:
print(i)