首页 > 解决方案 > 什么情况下类成员函数不将self作为第一个参数传递?

问题描述

问题

我正在使用一个库来促进客户端与服务器的 websocket 通信。

例如

from websocket import WebSocketApp
import websocket
class X(object):

    def run(self):
        self.ws  = WebSocketApp('wss://api.bitfinex.com/ws/2'
                            ,on_open=self.on_open
                            ,on_message=self.on_message
                            ,on_error=self.on_error
                            ,on_close=self.on_close)
        websocket.enableTrace(True)
        self.ws.run_forever()


    def on_open(self, ws):
        print('open')
    def on_close(self, ws):
        print('close')
    def on_message(self, ws, message):
        print('message')
    def on_error(self, ws, error):
        print('error')


if __name__=='__main__':
    x = X().run()

输出

error from callback <bound method X.on_open of <__main__.X object at 0x7fd7635e87f0>>: on_open() missing 1 required positional argument: 'ws'
  File "/home/arran/.local/lib/python3.6/site-packages/websocket/_app.py", line 343, in _callback
callback(*args)

我可能在这里遗漏了一些基本的东西。但任何帮助将不胜感激

编辑

看起来这可能是 websocket-client 库的版本特定问题https://github.com/home-assistant/home-assistant/issues/17532

我已降级到早期版本并解决了我的问题。不过,我仍然很想知道这个问题是如何出现的。我的理解是类实例方法总是将self作为第一个参数传递

标签: python

解决方案


这似乎是 WebSocket 类没有传递您的 on_open 方法所期望的 ws 参数的问题。我试图用我自己的虚拟类重现它,它工作正常。

class WS:
    def __init__(self, on_call):
        self.on_call = on_call
    def call(self):
        print("hi")
        self.on_call(self)


class X:
    def on_call(self, ws):
        print(ws)
    def run(self):
        self.ws = WS(self.on_call)
        self.ws.call()

X().run()
hi
<__main__.WS instance at 0x029AB698>

推荐阅读