内容简介:我们看看生成器的调用以及内部响应,外部访问生成器的send方法,类似于我们方位迭代器的next方法。内部响应的过程是,yield作为表达式使用。生成器重新运行时,yield方法返回一个值,如果send方法被使用,则返回none。
我们看看生成器的调用以及内部响应,
外部访问生成器的send方法,类似于我们方位迭代器的next方法。
内部响应的过程是,yield作为表达式使用。生成器重新运行时,yield方法返回一个值,如果send方法被使用,则返回none。
比如这样的过程,
def repeater(value):
while True:
new = (yield value)
if new is not None :
value = new
r= repeater(42)
print(r.__next__())
print(r.send('瞅你咋地!'))
输出
42 瞅你咋地!
我们写生成器时,还需要有两个方法,throw和close。
throw抛出异常,close方法停止生成器。对于,以前旧的代码不包含生成器的,我们需要模拟生成器,以兼容程序。
这样使用,
def myCommonFlatten(seq):
result =[]
try:
try: seq+''
except TypeError:pass
else:raise TypeError
for list in seq:
for item in myCommonFlatten(list):
result.append(item)
except TypeError:result.append(seq)
return result
strSeq=['张道陵',['葛玄',['萨守坚','许旌阳']]]
for item in myCommonFlatten(strSeq):
print(item)
输出
张道陵 葛玄 萨守坚 许旌阳
工程文件下载: https://download.csdn.net/download/yysyangyangyangshan/10823478
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Smashing Book
Jacob Gube、Dmitry Fadeev、Chris Spooner、Darius A Monsef IV、Alessandro Cattaneo、Steven Snell、David Leggett、Andrew Maier、Kayla Knight、Yves Peters、René Schmidt、Smashing Magazine editorial team、Vitaly Friedman、Sven Lennartz / 2009 / $ 29.90 / € 23.90
The Smashing Book is a printed book about best practices in modern Web design. The book shares technical tips and best practices on coding, usability and optimization and explores how to create succes......一起来看看 《The Smashing Book》 这本书的介绍吧!