Python 生成器 yield

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
 

 

posted @ 2012-04-09 16:24  谷安  阅读(160)  评论(0编辑  收藏  举报