将更多参数传递给这种类型的 python 函数

jef*_*ind 4 python function parameter-passing python-2.7

我认为这是非常基本的,但似乎无法弄清楚如何向谷歌提出正确的问题。我正在使用这个 python websocket 客户端来建立一些 websocket 连接。让我们假设我正在使用类似于该页面的代码示例:

import websocket
import thread
import time

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws):
    print("### closed ###")

def on_open(ws):
    def run(*args):
        ws.send("Hello")
        time.sleep(1)
        ws.close()
        print("thread terminating...")
    thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://echo.websocket.org/",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()
Run Code Online (Sandbox Code Playgroud)

所以我想要做的是向on_open函数添加更多参数,如下所示:

def on_open(ws, more_arg):
    def run(*args):
        ws.send("Hello %s" % more_arg)
        time.sleep(1)
        ws.close()
        print("thread terminating...")
    thread.start_new_thread(run, ())
Run Code Online (Sandbox Code Playgroud)

但我不知道如何传递这些参数,所以我在主线程中尝试:

ws.on_open = on_open("this new arg")
Run Code Online (Sandbox Code Playgroud)

但我收到错误:

类型错误:on_open() 正好需要 2 个参数(给定 1 个)

我将如何将这些新参数传递给我的on_open函数?

cs9*_*s95 5

请记住,您需要分配回调。您正在调用一个函数并将返回值传递给ws,这是不正确的。

您可以使用functools.partial将函数柯里化为高阶函数:

from functools import partial

func = partial(on_open, "this new arg")
ws.on_open = func
Run Code Online (Sandbox Code Playgroud)

func被调用时,它会调用on_open与第一个参数"this new arg",然后传递到任何其他参数funcpartial有关更多详细信息,请查看doclink中的实现。


Net*_*ave 5

您可以使用 alambda来包装调用:

ws.on_open = lambda *x: on_open("this new arg", *x)
Run Code Online (Sandbox Code Playgroud)