Files
Python_CookBook_repo/4.迭代器与生成器/6.定义带有额外状态的生成器函数.py
2025-09-10 16:12:45 +08:00

39 lines
1.4 KiB
Python
Raw 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.

from collections import deque
if __name__ == "__main__":
# 在学到了生成器函数以后,有一个巨大陷阱那就是尝试用生成器函数解决一切问题
# 当生成器函数需要与外界交互的时候,就会让它非常复杂
# 所以生成器我们就让它安心生成,在需要记录或者与外界交互的时候,写一个生成器类
class FbbIterClass:
def __init__(self,nums, history_len=3):
self.nums = nums
self.history = deque(maxlen=history_len)
def __iter__(self):
a0, a1 = 1, 1
index = 0
while index < self.nums:
self.history.append(a0)
yield a0
a0, a1 = a1, a0 + a1
index += 1
fbbs = FbbIterClass(5)
# 先用生成器生成,结果在生成的过程中会存入历史队列
for i in fbbs:
print(i)
# 当然在使用for之外的方法进行迭代时需要额外套一层iter来转发请求到__iter__()
fbb_iter = iter(fbbs)
print(fbb_iter.__next__())
print(fbb_iter.__next__())
print(fbb_iter.__next__())
print(fbb_iter.__next__())
print(fbb_iter.__next__())
# 这种方法的好处是,可以在迭代时随时暴露一些东西给外部程序,比如属性和状态
for line in fbbs.history:
print("history{}".format(line))