Callback not called if it is a class method

时间:2016-10-09 15:59:24

标签: python python-2.7

Python newbie question: the callback method handlePackets never gets called if it is a class method. If it is not in a class it works fine. What can I do?

class Receiver:

    def __enter__(self):
        self.serial_port = serial.Serial('/dev/ttyUSB0', 115200)
        self.xbee = ZigBee(self.serial_port, escaped=True,    callback=self.handlePackets)
        Logger.info('Receiver: enter')
        return self

    def __exit__(self ,type, value, traceback):
        Logger.info('Receiver: exit')
        self.serial_port.close()

    def handlePackets(data):
        Logger.info('Receiver: packet incoming')

2 个答案:

答案 0 :(得分:0)

我敢打赌这是因为,无论是在ZigBee内调用你的回调,都会默默地失败。解释器使用2个参数调用您的函数,但正如您已定义它 - 它只需要一个。

def handlePackets(self, data):
                 #^^^^

答案 1 :(得分:0)

我必须将self作为第一个参数添加到packetHandler。这是所有类方法都需要的,我忘了把它放进去。