Amazing Python 1: "yield"

1917 ワード

"yield"is used for Generater (below 2.2) or seperately (2.2 or above) in Python.
"yield"mainly works as "return", but it makes a function able to have multiple return values step by step .
All return values will comprise a sequence which can be used in "for"or more amazingly as a "link" by running "link.next()"!
 
Example 1:
def generater():
    yield 1
    yield 2
    yield 3
    
for i in generater():
    print i,
print "
" print "getnerater() =", generater() print "list(generater()) =", list(generater()) print link = generater() print "link.next() =", link.next() print "link.next() =", link.next() print "link.next() =", link.next()

Output:
1 2 3 

getnerater() = 
list(generater()) = [1, 2, 3]

link.next() = 1
link.next() = 2
link.next() = 3

Example2, calculating fibonacci(20):
(from speech "Object-oriented design with Python"by Bruce Eckel, 2005, http://us.pycon.org/talks/2005/wed/track1/44/talkDetails )
def fibonacci(count):
    def fib(n):
        if n < 2: return 1
        return fib(n-2) + fib(n-1)
    n = 0
    while n < count:
        yield fib(n)
        n += 1

for f in fibonacci(20): # Automatically iterable
    print f,

Output:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 

 
Example3, let's forget about recursion!
(from "Dive into Python, e.g. 17.19")
def fibonacci(n):
    a, b = 1, 1
    for i in range(n):
        yield a 
        a, b = b, a+b

for f in fibonacci(20):
    print f,

Output:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765