您的位置:首页 > 编程语言 > Python开发

Python 生成器 yield

2012-04-09 16:24 399 查看
Example1:

def fibonacci():
a, b = 0, 1
while True:
print 'abc'
yield b
a, b = b, a+b

fib = fibonacci()
fib.next()

[fib.next() for i in range(10)] #感觉这种写法很精妙

Example 2: yield 作为表达式 Send 来填充 yield表达式,throw 抛出异常,close抛出GeneratorExit异常

def psychologist():
print 'Please tell me your problems'
while True:
answer = yield
if answer is not None:
pass
if answer.endswith('?'):
print("Don't ask yourself too much questions")
elif 'good' in answer:
print('A that\'s good,go on')
elif 'bad' in answer:
print('Don\'t be so negative')

free = psychologist()
free.next()
free.send('I feel bad')
free.send('I feel good')

>>> Please tell me your problems
Don't be so negative
A that's good,go on

def myGenerator():
try:
yield 'something'
except ValueError:
yield 'dealing with the exception'
finally:
print 'ok let\'s clean'

gen = myGenerator()
gen.next()
gen.throw(ValueError('abcde'))
gen.close()

>>> something
dealing with the exception
ok let's clean
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: