如何在不调用的情况下将值传递给 python 函数?

Bil*_*ins 6 python parameters function

我无法找到合理的方法来创建调用需要参数的函数的变量。

这是我的代码的简化版本。我想在调用它时print_hello打印,而不是在定义它时打印。hello

print_hello = print('hello')
Run Code Online (Sandbox Code Playgroud)

当我定义时print_hello,它会调用print('hello'). 当我打电话时print_hello,它给了我一个错误。我该如何解决?

Sha*_*ger 9

如果您只想要一个能够精确执行您所描述的功能的函数,Sheldore 的答案是最简单的方法(并且比使用命名更Pythonic lambda)。

另一种方法是对函数进行部分应用functools.partial,它允许您在调用时传递附加参数:

from functools import partial

print_hello = partial(print, "hello")

print_hello()  # Prints "hello" to stdout

print_hello(file=sys.stderr)  # Prints "hello" to stderr

print_hello("world")  # Prints "hello world" to stdout
Run Code Online (Sandbox Code Playgroud)


Pau*_*ney 7

只需定义print_hello为 lambda 函数即可

>>> print_hello = lambda: print('hello')
>>> print_hello()
hello
Run Code Online (Sandbox Code Playgroud)

要延迟执行,您必须将调用包装到print另一个函数中。lambda 比定义另一个函数的代码更少。

注意 pep08建议在分配给变量时使用 def 函数而不是 lambda。看这里。所以@Sheldores 的回答可能是正确的选择。

  • 尽管如此,这最终会得到一个命名的 lambda,这与 PEP8 相悖 (3认同)