【发布时间】:2019-03-02 00:29:25
【问题描述】:
问题
我正在使用一个库来促进客户端与服务器的 websocket 通信。
websocket 库允许您指定套接字打开、关闭、出错或接收消息时的回调函数
如果我将我的回调函数设置为另一个类的实例函数,那么它们在被调用时需要传递 self 参数。
我已经明白,如果你调用一个类实例方法,它总是将 self 作为第一个参数传递。但是,我的回调没有通过 self
例如
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
【问题讨论】:
-
.on_open()is 正在传递self- 请注意,错误消息是在抱怨第二个参数ws。这完全是由于WebSocketApp没有使用参数调用该回调。 -
你用于 websocket 的 pypi 包的链接是什么?
-
好的,我明白你们在说什么。他们改变了界面。感谢您的帮助
标签: python