将 class 中的数据传递给 def

Passing data from within a class into def

当我 运行 binance.py 文件时,出现如下错误。我正在 class 中发送数据。我该如何解决这个问题?

import websockets
from binance.client import Client
from binance.websockets import BinanceSocketManager


class BinanceFutures(object):
    print("binance futures class")
    # websocket start
    futures_api_key = "oooo"
    futures_secret_key = "ppppp"
    client = Client(futures_api_key, futures_secret_key)
    bm = BinanceSocketManager(client)
    conn_key = bm.start_trade_socket('BNBBTC', process_message)
    bm.start()


    def process_message(self, msg):
        print("message type: {}".format(msg['e']))
        print(msg)
        # do something


if __name__ == "__main__":
    print("binance main")

我得到的错误:

Traceback (most recent call last):
  File "binancetest.py", line 6, in <module>
    class BinanceFutures:
  File "binancetest.py", line 13, in BinanceFutures
    conn_key = bm.start_trade_socket('BNBBTC', process_message)
NameError: name 'process_message' is not defined

意思是,你还没有定义名称process_message,如果你在class或文件中的某处定义它,错误将停止

您没有正确定义或使用 Python class

我认为你需要这样做(未经测试)。我添加了一个 __init__() 方法来在创建 class 实例时对其进行初始化。特别要注意我是如何将 self. 前缀添加到传递给 bm.start_trade_socket()self.process_message 参数的,因为它是 class.

的一种方法

您可能还需要使 bm 成为实例属性。 (即 self.bm 所有被引用的地方。)

import websockets
from binance.client import Client
from binance.websockets import BinanceSocketManager


class BinanceFutures:
    def __init__(self):
        print("binance futures class")
        # websocket start
        futures_api_key = "oooo"
        futures_secret_key = "ppppp"
        client = Client(futures_api_key, futures_secret_key)
        bm = BinanceSocketManager(client)
        conn_key = bm.start_trade_socket('BNBBTC', self.process_message)
        bm.start()

    def process_message(self, msg):
        print("message type: {}".format(msg['e']))
        print(msg)
        # do something


if __name__ == "__main__":
    print("binance main")