我正在使用 python 3。并且想知道附加到 pypubsub Sendmessage 命令的消息数据是通过引用还是通过值发送?它似乎是通过引用发送的,但我想知道是否有人可以验证这一点。
文档还说“消息不变性:侦听器必须保持消息内容不变,但 PyPubSub 不验证这一点”
下面的代码示例表明正在发送对消息数据参数的引用,并且修改这些数据会修改原始数据(而不是传递的数据副本)。为什么在侦听器例程中修改消息数据是个坏主意?
from pubsub import pub
class widget():
def __init__(self):
self.thingy = [{'biz':0},{'baz':1},{'buz':2}]
pub.subscribe(self.listen_for, 'wodget')
def listen_for(self, arg1):
print('wodget heard')
print(self.thingy)
print(arg1)
def send_thingy(self):
arg1 = self.thingy
pub.sendMessage('widget',arg1=arg1)
class wodget():
def __init__(self):
self.thongy = None
pub.subscribe(self.listen_for, 'widget')
# listen calendar
def listen_for(self, arg1):
print('widget heard')
print(arg1)
self.thongy = arg1
self.thongy[1]['baz']=99
print(arg1)
print(self.thongy)
arg1 = self.thongy
pub.sendMessage('wodget',arg1=arg1)
if __name__ == "__main__":
aWidget = widget()
aWidget.send_thingy()
aWodget = wodget()
aWidget.send_thingy()