Passing an object as an argument, how do I update my variables when using yield?

When using the following code for demo purposes only:

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()

If used return rsinstead yield rs, I can update the value of the status of the c dispatch(self, res) method of the resource class , outside of this there is something like:

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

But if you use yield rs, I can not update the status value , I always get the original value, for example:

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

Therefore, I would like to know how to update the object variables of an object passed as a reference when using yield .

+3
source share
2 answers

. .

>>> 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))
+4

yield, python, dispatch() .

, worker.dispatch(res), ( print worker.dispatch(res), ).

, falsetru.

. Python

+2

All Articles