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

时间:2019-06-03 23:11:38

标签: python function parameters

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

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

print_hello = print(‘hello’)

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

4 个答案:

答案 0 :(得分:3)

您需要定义一个函数。在python中,使用def定义了一个函数,如下面出于您的目的的简单示例所示。然后,您可以使用函数名称和()(例如print_hello())来调用函数。

def print_hello(): # <--- Does not accept an argument 
    print('hello')

print_hello()    # <--- No argument is passed
# hello

另一个示例,可让您更多地了解如何将参数传递给函数。您可以定义一个包含要打印的字符串的变量,假设为to_print,然后在调用它时将其作为参数传递给函数。尽管解释更多细节不在此答案的范围内,但我给出的两个示例应该可以帮助您入门。有关更多详细信息,您可以参考官方文档here

def print_hello(to_print): # <--- Accepts an argument 
        print(to_print)

to_print = "hello"
print_hello(to_print) # <--- Argument is passed
# hello

答案 1 :(得分:3)

只需将print_hello定义为lambda函数

>>> print_hello = lambda: print('hello')
>>> print_hello()
hello

要延迟执行,您必须在另一个函数中包装对print的调用。 Lambda比定义另一个函数要少。

注意pep08建议在分配给变量时使用def函数而不是lambda。参见here。因此,@ Sheldores answer可能是可行的方式。

答案 2 :(得分:3)

如果您只想要一个功能完全符合您的描述,Sheldore's answer is the simplest way to go

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

答案 3 :(得分:1)

您可以使用lambda表达式:

print_hello = lambda: print('hello')

或实际的函数定义:

def print_hello(): print('hello')

functools.partial (这是不同的,因为您仍然可以对print使用其他参数,而除非在定义中指定,否则您会失去其他功能)

from functools import partial
print_hello = partial(print, 'hello')

要使用以下任何一项:

print_hello()
#'hello'