gpt4 book ai didi

python - 在将对象作为参数传递时,如何在使用 "yield"时更新其变量?

转载 作者:太空宇宙 更新时间:2023-11-03 13:45:12 25 4
gpt4 key购买 nike

仅出于演示目的使用以下代码时:

from uuid import uuid4


class router(object):

def route(self):

res = response(jid=str(uuid4()))

worker = resource()
worker.dispatch(res)

print '[jid: %s, status: %s]' % (res.jid, res.status)


class response(object):

def __init__(self, jid):
self.jid = jid
self.status = 0


class resource(object):

def __init__(self):
self.status = 200

def dispatch(self, res):
res.status = self.status
rs = 'ok'
#return rs
yield rs


app = router()
app.route()

如果使用 return rs 而不是 yield rs 我可以在 dispatch(self, res) resource 类的方法,输出类似于:

[jid: 575fb301-1aa9-40e7-a077-87887c8be284, status: 200]

但是如果使用 yield rs 我无法更新 status 的值,我总是得到原始值,例如:

[jid: 575fb301-1aa9-40e7-a077-87887c8be284, status: 0]

因此我想知道,在使用 yield 时,如何更新作为引用传递的对象的对象变量。

最佳答案

您需要迭代生成器。否则生成器不会被执行。

>>> def gen():
... print(1)
... yield 'blah'
... print(2)
...
>>> g = gen() # No print (not executed)
>>> next(g) # print 1, yield `blah`. execution suspended.
1
'blah'

替换以下行:

worker.dispatch(res)

与:

for rs in worker.dispatch(res):
pass

next(worker.dispatch(res))

关于python - 在将对象作为参数传递时,如何在使用 "yield"时更新其变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21704356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com