Python 使用'生成一个项目;行不通

Python 使用'生成一个项目;行不通,python,iterator,generator,python-2.x,yield,Python,Iterator,Generator,Python 2.x,Yield,使用时: from bottle import route, run, request, view N = 0 def yielditem(): global N for i in range(100): N = i yield i @route('/') @view('index.html') def index(): print yielditem() print N run(host='localhost',

使用时:

from bottle import route, run, request, view

N = 0

def yielditem():
    global N
    for i in range(100):
        N = i
        yield i

@route('/')
@view('index.html')
def index():
    print yielditem()
    print N    

run(host='localhost', port=80, debug=False)
页面
index.html
已成功显示,但
yield
部分不工作:

  • N
    对于每个新请求始终保持为0

  • 打印yielditem()
    给出

如何使这个
产生
在这个Python上下文中正常工作?


我期望的是:
0
应该在第一次请求时打印,
1
应该在第二次请求时打印,等等。

看起来您打印的是生成器本身,而不是它的值:

from bottle import route, run, request, view

N = 0
def yielditem():
    global N
    for i in range(100):
        N = i
        yield i

yf = yielditem()

@route('/')
@view('index.html')
def index():
    print next(yf)
    print N    

run(host='localhost', port=80, debug=False)

看起来您正在打印生成器本身,而不是其值:

from bottle import route, run, request, view

N = 0
def yielditem():
    global N
    for i in range(100):
        N = i
        yield i

yf = yielditem()

@route('/')
@view('index.html')
def index():
    print next(yf)
    print N    

run(host='localhost', port=80, debug=False)
这和瓶子没有任何关系,只是发电机的功能

当调用
yielditem()
时,正如Python告诉您的那样,您会得到一个生成器对象
yielditem
。它不会神奇地开始在上面迭代

如果确实要在generator对象上进行迭代,则必须使用类似于
print(next(yielditem())
的方法显式执行此操作

如何使用该生成器是另一回事:如果要在多个函数调用期间访问同一个生成器对象,可以将其放置在调用的函数之外:

generator_object = yielditem()

def print_it():  # this is like your `index` function
    print "Current value: {}".format(next(generator_object))

for x in range(10):  # this is like a client reloading the page
    print_it()
这和瓶子没有任何关系,只是发电机的功能

当调用
yielditem()
时,正如Python告诉您的那样,您会得到一个生成器对象
yielditem
。它不会神奇地开始在上面迭代

如果确实要在generator对象上进行迭代,则必须使用类似于
print(next(yielditem())
的方法显式执行此操作

如何使用该生成器是另一回事:如果要在多个函数调用期间访问同一个生成器对象,可以将其放置在调用的函数之外:

generator_object = yielditem()

def print_it():  # this is like your `index` function
    print "Current value: {}".format(next(generator_object))

for x in range(10):  # this is like a client reloading the page
    print_it()