将更多参数传递给这种类型的python函数 [英] Passing more arguments to this type of python function
问题描述
我认为这是非常基本的,但即使是如何向Google提出正确的问题,也似乎无法弄清楚.我正在使用此python websocket客户端建立一些websocket连接.假设我正在使用与该页面相似的代码示例:
I figure this is pretty basic, but can't seem to figure out even how to ask google the right question. I am using this python websocket client to make some websocket connections. Let's just assume I'm using the code example similar to that page:
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()
所以我想做的是向on_open
函数添加更多参数,如下所示:
So what I am trying to do is add more arguments to the on_open
function, something like this:
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, ())
但是我不知道如何传递这些参数,所以我尝试了主线程:
But i can't figure out how to pass these arguments in, so I tried in the main thread:
ws.on_open = on_open("this new arg")
但是我得到了错误:
TypeError:on_open()恰好接受2个参数(给定1个参数)
TypeError: on_open() takes exactly 2 arguments (1 given)
我如何将这些新参数传递给我的on_open
函数?
How am I going to pass these new arguments to my on_open
function?
推荐答案
请记住,您需要分配一个回调.相反,您正在调用一个函数,并将返回值传递给ws
,这是不正确的.
Keep in mind that you need to assign a callback. You are instead calling a function and passing the return value to ws
, which is incorrect.
您可以使用 functools.partial
来功能更高的一个:
You can use functools.partial
to curry a function to a higher order one:
from functools import partial
func = partial(on_open, "this new arg")
ws.on_open = func
当调用func
时,它将调用on_open
,第一个参数为"this new arg"
,然后再传递给func
的任何其他参数.在文档链接中查看partial
的实现以获取更多详细信息.
When func
is invoked, it will invoke on_open
with the first argument as "this new arg"
, followed by any other arguments passed to func
. Look at the implementation of partial
in the doclink for more details.
这篇关于将更多参数传递给这种类型的python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!