0

好吧,伙计们,我正在测试一个非常简单的 PyDispatch 信号设置,但似乎无法弄清楚为什么我每次发送一个信号时都会收到多个信号。

代码:

class Strategy():

def __init__(self,name,exchange=Exchange(), system=System()):
    self.SIGNAL='Strategy'
    self.SENDER = 'Strategy'
    self.system = system
    self.name = name
    self.connect_to_system()


def connect_to_system(self):
    dispatcher.connect(self.receive_message, signal='System', sender='System')
    self.system.connect_strategy(self.name)

def send_message(self,info, strategy):
    print 'send strat'
    dispatcher.send(signal=self.SIGNAL,sender=self.SENDER,info=info,strategy=strategy)

class System():
    def __init__(self,exchange=Exchange()):
        self.SIGNAL='System'
        self.SENDER='System'
        dispatcher.connect(self.receive_message, signal=dispatcher.Any, sender=dispatcher.Any)

    def receive_message(self, sender, signal, **kwargs):
        if sender == 'Strategy':
            print kwargs, sender, signal

这给了我:

In [10]: strat.send_message("OK",'sender')
send strat
{'info': 'OK', 'strategy': 'sender'} Strategy Strategy
{'info': 'OK', 'strategy': 'sender'} Strategy Strategy
{'info': 'OK', 'strategy': 'sender'} Strategy Strategy
{'info': 'OK', 'strategy': 'sender'} Strategy Strategy
4

1 回答 1

0

Answer:

In my code, using:

def __init__(self,name,exchange=Exchange(), system=System()):

Causes us to call the System(), even when I'm initializing it later myself. I need to just use exchange, system in this instance. I was calling the same init in other classes.

On import, it was running 3 times from those calls and then the 4th was the time I actually wanted it to.

于 2013-06-28T17:21:17.713 回答