我一直在阅读 Python 中的弱引用和强引用,特别是关于看起来像的错误
ReferenceError: weakly-referenced object no longer exists
在这里,我有一个基本的 RPC 接口,它将对象从客户端传递到服务器,然后服务器将这些对象保存到预定义的类中。这是我的代码中所有结构的基本概述。注意“标志”的行为:
客户端:
# target = 'file.txt', flags = [(tuple, tuple), (tuple, tuple)]
def file_reminder(self, flags, target):
target = os.path.abspath(target)
c = rpyc.connect("localhost", port)
# flags can be referenced here
return c.root.file_reminder(flags, target)
服务器端:
class MyService(rpyc.Service):
jobs = EventLoop().start()
# this is what's called from the client side
def exposed_file_reminder(self, flags, target):
reminder = FileReminder(flags, target)
self.jobs.add_reminder(reminder)
# reminder.flags can be referenced here
return "Added a new reminder"
class FileReminder(object):
def __init__(self, flags, target):
self.flags = flags
self.target = target
def __str__(self):
return str(self.flags) + target
class EventLoop(threading.Thread):
def __init__(self):
self.reminders = []
def add_reminder(self, reminder):
# reminder.flags can be referenced here
self.reminders.append(reminder)
def run(self):
while True:
for reminder in self.reminders:
# reminder.flags is no longer defined here
print reminder
这里的问题是“flags”参数在线程中打印(或在线程的 run() 函数中以任何方式操作)时总是抛出 ReferenceError。注意,目标处理得很好。当我将“标志”更改为不可变的(如字符串)时,不会弹出 ReferenceError。这让我头疼,所以任何帮助都将不胜感激!