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

时间:2015-03-19 18:22:58

标签: python twisted twisted.internet

我有一个带有两个方法的类A,method_one使用defer和method_two,在回调函数中我将一个值设置为self.value并将其添加到defer的回调链中。但在此之后,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

提前感谢: - )

1 个答案:

答案 0 :(得分:3)

问题在于,method_one被推迟,因此,不是立即调用set_self_value,而是首先转到下一步a.method_two(),因此当时值为method_two还没有设置你得到一个空列表。

确保在method_oneimport 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

{{1}}

<强>输出:

{{1}}