迭代器:
from collections import Iterable
from time import sleep
# 判断是否是一个可迭代的对象
# print(isinstance([11, 22], Iterable))
class Classmate(object):
def __init__(self):
self.names = list()
self.num = 0
def add_name(self, name):
self.names.append(name)
# 迭代器--->有__iter__和__next__两个方法的类叫迭代器
def __iter__(self):
"""如果想要一个对象成为一个 可迭代的对象,即 可以使用for,则必须实现__iter__方法"""
# 返回时 自动创建Classiterator对象,并把Classmate类中的self传递给Classiterator,执行Classiterator中的next方法
return self # 返回自己本身
def __next__(self):
if self.num < len(self.names):
re = self.names[self.num]
self.num += 1
return re
else:
raise StopIteration
if __name__ == '__main__':
classmate = Classmate()
classmate.add_name("老王")
classmate.add_name("老徐")
classmate.add_name("老张")
for name in classmate:
print(name)
sleep(1)
生成器: 一个特殊的迭代器
def filbo(all_num):
a, b, count = 0, 1, 0
while count < all_num:
# 函数中带有yield语句 这个就不再是函数,则为生成器的模板,当执行时,遇到yield时,执行暂停,等到下次再次执行的时候,从暂停处继续向下运行
yield a
a, b = b, a+b
count += 1
# 如果在调用filbo时,发现函数中有yield时,怎不再是调用函数,而是创建一个生成器对象
f = filbo(10)
for i in f:
print(i)
生成器中的__next__() 和 send():
def filbo(all_num):
a, b, count = 0, 1, 0
while count < all_num:
ret = yield a
print(ret)
a, b = b, a + b
count += 1
# 如果在调用filbo时,发现函数中有yield时,怎不再是调用函数,而是创建一个生成器对象
f = filbo(10)
# 执行到yield时,a = 0 的值传递给f.__next(),之后程序暂停
a = f.__next__()
print(a)
# 再次执行时,从上次暂停的位置继续运行,即先把"$$$$$$$$$$$$"传给ret后,直至再次运行到yield时,a = 1 的值传递给f.send()
b = f.send("$$$$$$$$$$$$")
print(b)
运行结果: