python - 什么情况下类成员函数不将self作为第一个参数传递?
问题描述
问题
我正在使用一个库来促进客户端与服务器的 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作为第一个参数传递
解决方案
这似乎是 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>
推荐阅读
- github - 在 GitHub 上的 PR 操作期间,实际运行的是哪个版本的代码?
- amazon-web-services - 为什么导出 s3 存储桶名称和 arn 在无服务器框架中使用不同的语法?
- r - 过滤不包含特定条件的变量
- android - Developing with Cordova can I use Android Studio on Windows 10 and Ubuntu for Windows together?
- c - 关于局部变量的意外输出
- c - int 返回内存位置/地址吗?
- vue.js - 动态路线,但不是传统意义上的路线
- firebase - Firebase 中的“写”是什么?
- r - 使用 R 中的剪切函数剪切数据时显示空组
- ruby-on-rails - 如何在 reactJS 中处理重定向?