python生成器的原理探究
python生成器的原理探究
本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。
1、概念
生成器是通过使用yield语句而不是return语句定义一个普通函数来创建的。如果函数包含至少一个yield语句,它就成为一个生成器函数。yield和return都将从函数返回一些值。函数在执行return时终止,而yield语句暂停函数,保存它的所有状态,然后在后续调用时继续执行。
2、组成
至少有一个yield语句。
返回一个对象(迭代器),但不立即开始执行。
记住连续调用之间的局部变量及其状态。
实现迭代协议。
3、原理分析
下面是使用生成器的类似内容。可以发现,调用__iter__()和__next__()都是由生成器自动处理的:
#Generatorfornextpoweroftwo.
defNextPowTwo(max_ele):
n=0
whilen yield2*n n+=1 raiseStopIteration obj=NextPowTwo(20) print(obj.next()) print(obj.next()) print(obj.next()) print(obj.next()) 在对于python学习的时候,容易把生成器与别的知识点混淆,其实想要判断有个最简单的方法,看看是否使用yield函数就知道了。 以上就是python生成器的原理探究,相信现在已经能够通过yield来明确生成器的使用了。同时我们可以发现,生成器在自动处理调用上是非常好用的。更多Python学习教程请关注IT培训机构:千锋教育。

猜你喜欢LIKE
相关推荐HOT
更多>>
python如何创建UDP服务器和客户端?
python如何创建UDP服务器和客户端?本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、创建UDP服务端的基本步骤(1)创建套接字并绑定...详情>>
2023-11-10 21:18:09
python条件判断分为哪几类?
python中条件判断分为哪几类?python中条件判断分为单项判断,双向判断和多向判断。1、单项判断单项判断最基本的就是if。stone=6ifstone>=6:prin...详情>>
2023-11-10 19:15:56
python多进程与多线程的简单区分
python多进程与多线程的简单区分1、区别多进程与多线程不同在于,多进程的每一个进程都有一份变量的拷贝,进程之间的操作互不影响。2、实例impo...详情>>
2023-11-10 16:04:13
python-=是什么意思
python中-=是什么意思当我们看到python中类似数学的算数符号时,如果是有加减的出现,就可以明确它们是赋值运算符的一种。本篇所要带来的是-=,...详情>>
2023-11-10 14:36:01热门推荐
技术干货






