gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 16:33:49 24 4
gpt4 key购买 nike

我有一个类 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/

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