python generator注意事项_【Python注意事项】如何理解python中间generator functions和yield表情...

Python支持的generator functions语法同意我们定义一个行为与iterator类似的函数,它能够被用在须要循环调用的场合。

与普通函数相比,generator functions仅仅是在函数定义中多了1个yield表达式。除此之外,没有其他特别之处。

当generator函数被创建时。python解释器会自己主动为它实现iteration protocol(实现__iter__和next方法,详细可參见python官网文档Iterator Types部分)以支持其被用于须要迭代的场合。

调用普通函数时,被调用函数一般会从函数体第1行開始运行并在遇到return或抛异常时退出,其内部变量也会随之销毁。

而generator functions被调用时,它会返回一个generator object,这个object被循环调用时,每次都会yield一个值,而非return一个值(由此带来的有异于普通函数的行为,会在下一小节介绍yield表达式时做具体说明)。

generator functions具有2个典型特性:

1) 懒惰求值。故节省内存,详见这篇文档Improved Performance部分的说明

2) 具有iterator的行为特性,故它能够被用在for循环中

比如在Python2.x中。若for循环的循环次数很大,为节省内存,我们一般会写出例如以下代码:

for idx in xrange(0, 100000000):

do something

这里的xrange()函数返回的是一个xrange对象(而range()则返回一个list对象),从概念上来看。该xrange对象是一个generator object。由于generator的上述2个特性。xrange object可用于for循环。且无论循环次数多大。它都仅仅占用极少量内存(由于它不会一次性生成包括n个元素的list)

须要注意的是:仅仅有在不须要频繁生成同一份数据集合的情况下(大部分应用都是这类case),generator function才干提供预期的性能优势;否则,其优势也可能转变为劣势。

通过以下的场景。相信能够帮助我们easy地理解这句话。

如果python进程生成1个整数的过程非常耗时,以下是一种调用sum和product的方式:>>> s = sum(xrange(1000000))

>>> p = product(xrange(1000000))       再对照还有一种实现方式:

>>> nums = list(xrange(1000000))

>>> s = sum(nums)

>>> p = product(nums)

非常显然,第1种方式调用sum和product时会分别生成1次元素为integer的大集合,而第2种方式仅仅会生成1次并存放在内存供兴许使用中。在我们的如果场景下。第2种方式会更节省时间(典型的空间换时间)。只是,如果机器内存受限以至于无法hold住大集合,则仅仅能採用第1种实现方式(时间换空间的折衷方式),即使其性能有损耗。

除支持generator functions外。python还支持generator expressions语法。关于generator的具体说明,强烈建议精读PYTHON

2. yield表达式

从官网文档可知,yield表达式仅仅能用于generator function的定义体中。也即。仅仅要某函数定义中出现了yield表达式。该函数就成了generator函数。而不再是个普通函数。我们能够从"yield"的字面含义来理解yield表达式的行为:程序运行至该表达式时,会临时"放弃"继续向下运行的权利,程序控制权会返回给其调用者且由yield表达式"产生"的值也会返回给caller,此外,函数运行yield表达式后挂起时的context(包含那个时刻函数的local scope和local variables等信息)会被保存下来以便兴许恢复运行现场(与CPU处理中断信号的过程很类似)。

当然。仅从字面意思判断yield表达式行为的思路并不严谨,这样解释仅仅是为了辅助理解。以下是PYTHON-

GENERATOR FUNCTIONS AND EXPRESSIONS一文中出现的关于generator functions和yield表达式行为的更严谨解释:Normal functions return a value and then exit. But generator functions automatically suspend and resume their execution. Because of that, they are often a useful alternative to both computing an entire series

of values up front and manually saving and restoring state in classes. Because the state that generator functions retain when they are suspended includes their local scope, their local variables retain information and make it available when the functions are

resumed.The primary difference between generator and normal functions is that a generator yields a value, rather than returns a value. The yield suspends the function and sends a value back to the caller while retains

enough state to enable the function immediately after the last yield run. This allows the generator function to produce a series of values over time rather than computing them all at once and sending them back in a list.

为更好地理解上面这段话,能够分析以下这段代码:>>> def create_counter(n):

print('create_counter()')

while True:

yield n

print('increment n')

n += 1

>>> c = create_counter(2)

>>> c

>>> next(c)

create_counter()

2

>>> next(c)

increment n

3

>>> next(c)

increment n

4

>>>       上面的代码用def定义了名为create_counter的generator function来实现计数器功能。

对象c是由create_counter创建出来的generator object。当调用python built-in函数next()时,它会调用其參数c的__next__方法。

备注:由第1小节的介绍可知,python解释器在创建generator object时会为其自己主动生成支持__next__的代码。

第1次调用next()时,c对象会运行yield n,其行为是函数体被挂起并将n返回给调用者。故能够看到第1次调用next()的输出并未包括"increment n"这个字符串。事实上。函数体挂起并返回时,其运行上下文会被记录下来,仅仅只是这一步我们无法显式感受到而已。

第2次调用next()时。generator function在上次挂起的地方恢复运行环境(本例中为n的值)后继续向下运行,故先输出"increment n"字符串。然后n+1,因为while loop的存在,因此程序又运行到yield n,它又会挂起并返回,故终端输出3第n次调用next()时。函数行为与第2次调用全然一致,此处不赘述。

真正理解了上面代码的输出后。相信我们也会真正理解yield表达式和generator function的语法行为。1) generators are used to generate a series of values2) yield is like the return of generator functions3) The only other thing yield does is save the "state" of a generator function4) A generator is just a special type of iterator5) Like iterators, we can get the next value from a generator using next()6) for gets values by calling next() implicitly相信有了本篇笔记前面的介绍。这几点非常easy理解。

以下是一段利用yield语法生成裴波纳契数列的代码。是不是非常pythonic呢? ^_^#!/bin/env python

def fib(threshold):

a, b = 0, 1

while a < threshold:

yield a

a, b = b, a + b

def main():

for n in fib(100):

print n

if '__main__' == __name__:

main()

========================= EOF =============================

版权声明:本文博主原创文章,博客,未经同意不得转载。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值