我尝试在python中定义一个用于管理WebSockets的类,这个docu-example正在使用
这是我的代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import websocket
import thread
import time
class WebSocket:
def on_message1(self, ws, message):
print message
def on_error1(self, ws, error):
print error
def on_close1(self, ws):
print "Socket Closed"
def start(self):
global ws
ws.run_forever()
def __init__(self, host, port):
self.host = host
self.port = port
websocket.enableTrace(True)
self.ws = websocket.WebSocketApp("ws://" + host+":"+port,
on_message = on_message1,
on_error = on_error1,
on_close = on_close1))
if __name__ == '__main__':
print "Error: create an instance of this class instead!"
但是当我运行代码时,我收到错误:
文件“/home/pi/ABC/CASCADE/WebSocketClientClass.py”,第37行, init
NameError:未定义全局名称“on_message1” 它被定义但不知何故不起作用......为什么?
感谢
答案 0 :(得分:1)
您在WebSocket类中定义了方法,因此要访问它,您需要self
,如下所示:
self.ws = websocket.WebSocketApp("ws://" + host+":"+port,
on_message = self.on_message1,
on_error = self.on_error1,
on_close = self.on_close1))