【问题标题】:Passing more arguments to this type of python function将更多参数传递给这种类型的 python 函数
【发布时间】:2018-01-22 05:12:48
【问题描述】:

我认为这是非常基本的,但似乎甚至无法弄清楚如何向谷歌提出正确的问题。我正在使用 this python websocket client 进行一些 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()

所以我想做的是向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, ())

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

ws.on_open = on_open("this new arg")

但我得到了错误:

TypeError: on_open() 只需要 2 个参数(给定 1 个)

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

【问题讨论】:

  • @cᴏʟᴅsᴘᴇᴇᴅ 是的,两者都有帮助,但我最终更喜欢你的 partial 用法,我会接受那个。

标签: python python-2.7 function parameter-passing


【解决方案1】:

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

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

from functools import partial

func = partial(on_open, "this new arg")
ws.on_open = func

当调用func 时,它将调用on_open,第一个参数为"this new arg",然后是传递给func 的任何其他参数。更多细节请查看文档链接中partial 的实现。

【讨论】:

  • 谢谢,是的,“回调”这个词是我想的。谢谢你,虽然我不得不说 Danial Sanchez 建议的 lambda 技术看起来很pythonic。
  • @jeffery_the_wind 是的......他们都是一样的。就个人而言,我不喜欢 lambdas :)
【解决方案2】:

您可以使用lambda 来结束通话:

ws.on_open = lambda *x: on_open("this new arg", *x)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 2016-02-25
    相关资源
    最近更新 更多