简体   繁体   English

Python将带有参数的函数作为参数传递给高阶函数?

[英]Python pass function with parameters as parameter to higher order function?

When ever I try to pass one function with parameter (test) to a function (await_char) the passod on function executes first skipping the runtime order of await_char ?每当我尝试将一个带有参数 (test) 的函数传递给函数 (await_char) 时,函数上的密码首先执行,跳过await_char的运行时顺序?

` `

def await_char(param, func="", msg=""):
    import keyboard
    if msg == "":
        msg_out = 'Press {} to continue'.format(param.upper())
    else:
        msg_out = msg
    print(msg_out)
    while True:
        if keyboard.is_pressed("c"):
            break
        if keyboard.is_pressed("C"):
            break
        if keyboard.is_pressed(param):
            if func:
                func()
            break


def test(msg):
    print(msg)


await_char("y", "press some button, like: Y", test("John"))

` `

I tried args, kwargs but I don't know how to make this optional parameter我尝试了 args、kwargs 但我不知道如何制作这个可选参数

Typically when you pass arguments to a function, those arguments are evaluated when the function is called.通常,当您将参数传递给函数时,这些参数会在函数被调用时求值。 In your case, you want a pointer to a function that will be called later.在您的情况下,您需要一个指向稍后将调用的函数的指针。 There are a few ways to do this, but the simplest and first that comes to mind is via the lambda operator.有几种方法可以做到这一点,但首先想到的最简单的方法是通过lambda运算符。 It allows you to create a nameless function and then use that unnamed function later.它允许您创建一个无名函数,然后在以后使用该无名函数。 But, more than that, when you define the unnamed function, you can pass whatever arguments you want to at the time of definition.但是,不仅如此,当您定义未命名函数时,您可以在定义时传递任何您想要的参数。

So, simplest change to your code is to change:因此,对代码进行的最简单更改是更改:

await_char("y", "press some button, like: Y", test("John"))

to:到:

await_char("y", "press some button, like: Y", lambda: test("John"))

Also, as a side note, please be consistent with your argument order.另外,作为旁注,请与您的论证顺序保持一致。 You define:您定义:

def await_char(param, func="", msg="")

but then later call it via await_char(param, msg, func) more or less... The order must be maintained, or you will get unexpected results.但后来或多或少通过await_char(param, msg, func)调用它......必须保持顺序,否则你会得到意想不到的结果。

Also, as a matter of taste, func="" is not the best default choice.此外,作为一个品味问题, func=""不是最好的默认选择。 Typically for a variable like func , None would be a more common default value.通常对于像func这样的变量, None是更常见的默认值。 "" for msg is a fine choice. "" for msg是一个不错的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM