twisted defer 使 class 实例变量的赋值无效

twisted defer make the assignment of class instance variables is invalid

我有一个 class A 有两个方法, method_one 使用延迟和 method_two ,在回调函数中我将值设置为 self.value 并添加它延迟的回调链。但在那之后 self.value 仍然是 method_two 中的原始值。总之回调函数中self.value的赋值是无效的

from twisted.internet import utils, reactor
class A(object):

    def __init__(self):
        self.value = []

    def method_one(self):
        d = utils.getProcessOutput('/bin/sh', ('-c', 'ls /home')) # return a defer
        def set_self_value(result):
            self.value = result.split()  # assign result.split() to self.value
        d.addCallback(set_self_value)

    def method_two(self):
        print self.value  # it is still [] rather than result

a = A()
a.method_one()
a.method_two()
reactor.run()

output:
[]  # i expect self.value is ['lost+found', 'user']
lost+found
user

提前致谢:-)

问题是,由于 method_one 被推迟,所以,它没有立即调用 set_self_value,而是先进入下一步 a.method_two(),因此与当时一样该值尚未设置,您会得到一个空列表。

要确保 method_twomethod_one 之后调用,请将其添加到回调链中:

import twisted
from twisted.internet import utils
from twisted.internet import reactor


class A(object):

    def __init__(self):
        self.value = []

    def method_one(self):
        d = utils.getProcessOutput('/bin/sh', ('-c', 'ls /home'))
        def set_self_value(result):
            print 'called set'
            self.value = 100
        d.addCallback(set_self_value)
        d.addCallback(self.method_two)

    def method_two(self, *args): # *args required to handle the result
        print 'called two'
        print self.value

def main():
    a = A()
    a.method_one()


reactor.callWhenRunning(main)
reactor.run()

输出:

called set
called two
100