Skip to main content
 首页 » 编程设计

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

2025年05月04日10sky-heaven

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

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

print_hello = print(‘hello’) 

当我定义‘print_hello’时,它调用print(‘hello’)。当我调用“print_hello”时,它给了我一个错误。我该如何解决这个问题?

请您参考如下方法:

如果您只想要一个完全符合您描述的功能,Sheldore's answer is the simplest way to go (比使用命名的 lambda 更 Pythonic)。

另一种方法是 make a partial application of the function with 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