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

标签 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

提前致谢:-)

最佳答案

问题在于,由于 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

关于python - twisted defer 使类实例变量的赋值无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29152236/

相关文章:

python - 排列数据以绘制 3D 曲面图

python - Twisted - 将协议(protocol)(和套接字句柄)对象传递给 Twisted 子进程

python - 高速公路 Asyncio ReconnectingClientFactory

python - 惰性延迟列表达到最大递归深度

python - 扭曲并将异常写入stderr

Python Twisted 客户端

python - 导入 azure.search.documents 时,Azure 函数未部署(时间触发器)

python - 无法将 datetime.strptime 与 from datetime import datetime 一起使用

python - 计算执行期间在 multiprocessing.Pool 中执行的任务总数

python - 为什么我得到 '_SIGCHLDWaker' object has no attribute 'doWrite' in Scrapy?