I\'m trying access some data using websockets, but I cannot really get around the examples given in the websockets documentation.
I have this code (https://pypi.org/proj
The WebSocketApp
needs callable objects for its callbacks (both the ones you pass in the constructor, like on_message
, and the one you're setting after the fact, on_open
).
Plain functions are callable objects, so your non-OO version works fine, because you're passing the plain functions.
Bound methods are also callable objects. But your OO version isn't passing bound methods. A bound method is, as the name implies, bound to an object. You do this by using the obj.method
notation. In your case, that's self.on_message
:
self.ws = websocket.WebSocketApp("ws://echo.websocket.org/",
on_message = self.on_message,
on_error = self.on_error,
on_close = self.on_close)
self.ws.on_open = self.on_open
However, you've got another problem. While this will make your error go away, it won't make your code actually work. A normal method has to take self
as its first argument:
def on_message(self, ws, message):
print message
It's also worth noting that you're not really using the class for anything. If you never access anything off self
, the class is just acting like a namespace. Not that this is always a bad thing, but it's usually a sign that you need to at least think through your design. Is there really any state that you need to maintain? If not, why do you want a class in the first place?
You may want to reread the tutorial section on Classes to understand about methods, self
, etc.