将类中的参数传递给回调函数

时间:2017-09-07 16:22:49

标签: python-3.x callback

假设我有一个websocket客户端,我想在打开连接时更新变量。

def on_open(ws):
    x += 1

def main():
    x = 0
    ws = websocket.WebSocketApp('wss://api2.poloniex.com/', on_message=on_message, on_error=on_error,on_close=on_close,on_open=on_open)
    ws.run_forever()

if __name__ == '__main__':
    main()

websocket库中的相关代码如下:

Class WebSocketApp(object):
    def __init__(self, url, header=None,
             on_open=None, on_message=None, on_error=None,
             on_close=None, on_ping=None, on_pong=None,
             on_cont_message=None,
             keep_running=True, get_mask_key=None, cookie=None,
             subprotocols=None,
             on_data=None):

        ...
        self.on_open = on_open
        ...

    def run_forever(self, sockopt=None, sslopt=None,
                ping_interval=0, ping_timeout=None,
                http_proxy_host=None, http_proxy_port=None,
                http_no_proxy=None, http_proxy_auth=None,
                skip_utf8_validation=False,
                host=None, origin=None):
        ... code to open socket ...

        self._callback(self.on_open)
        ...

    def _callback(self, callback, *args):
        if callback:
            callback(self, *args)

我无法确定如何通过" x"通过我定义的on_open函数。我认为修改我的本地版本的库不是一个好习惯。这里是websocket库的链接 - https://github.com/websocket-client/websocket-client/tree/master/websocket,该类位于_app.py文件中

编辑:在不使用全局变量的情况下寻找解决方案

1 个答案:

答案 0 :(得分:0)

class Counter:

    def __init__(self):
        self._value = 0

    def get_value(self):
        return self._value

    def inc_value(self):
        self._value += 1


def main():
    counter = Counter()

    def on_open(ws, x=counter):
        x.inc_value()

    ws = websocket.WebSocketApp('wss://api2.poloniex.com/', on_message=on_message, on_error=on_error,on_close=on_close,on_open=on_open)
    ws.run_forever()

if __name__ == '__main__':
    main()