生成器返回是一个可迭代的对象
from collections.abc import Iterable
from collections.abc import Iterator
def diedai():
a=[1,2,3,4,5]
for i in a:
yield i
a=diedai()
print(isinstance(a, Iterator))
注意:我在导入import Iterable和import Iterator警告DeprecationWarning: Using or importing the ABCs from ‘collections’ instead of from ‘collections.abc’,因为python3.8已经弃用从collections导入了,改为collections.abc导入
参考链接:https://blog.csdn.net/qq_38125058/article/details/86605232
在遇到这段代码的时候,很看不懂for element in yield_test(sublist) ,还有运行结果为什么到异常之后还会回到第二个for处
1.每一个递归在递的过程中运行到yield_test(sublist)都会暂停阻塞
2.比如列表[1,2],运行完第一个for之后,到第二个for处,调用yield_test函数,进入下一层,就会触发typeerror,因为for没法迭代一个数字,触发异常之后就会去运行异常步骤,yield nested生成一个1的迭代器,这个时候就会返回值到上一层,接着从暂停阻塞处执行,也就是第二个for处,接着执行接下来的步骤, yield element这个步骤再生成一个1,最后再在调用函数的地方用for迭代并打印出来
def yield_test(nested):
try:
for sublist in nested:
print('第一个for')
t=yield_test(sublist) #这通过异常步骤返回的是个迭代器
# print(t)
for element in t:
print('第二个for')
# print(element)
# pass
yield element
except TypeError:
print('异常')
# print(nested)
yield nested
# print(yield_test([1,2]))
for i in yield_test([1,2]):
print(i)