繁体   English   中英

如果不调用 function,为什么从 function 执行打印语句?

[英]Why the print statement is being executed from the function if the function is not called?

def enumerator(fruits):
    for index, fruit in enumerate(fruits):
        print(f"Fruit: {fruit}, under the index: {index}.")

just_a_variable = enumerator(["apple", "banana", "lemon"]) # Im just assigning function call
# to the variable "just_a_variable"
# and boom, when I run the program the function is called. Makes no sense (it shouldn't work this way, does it?)

我假设发生这种情况是因为 function 中有一个打印语句,但它仍然没有意义。 如果我将 print 语句更改为“return”,它突然无法编译,这就是我对使用 print 的期望。 我在这里错过了什么?

通常,如果您在 function 之后添加括号(如以下两个示例之一),则会调用它。

function_name(arguments)
variable = function_name(arguments)

如果你只是想让一个变量指向 function:

variable = function

那么以下两个语句将变得相同:

variable(arguments)
function(arguments)

话虽如此,这对我来说似乎有点没用。 你 function 定义了它当前的方式,我不知道有一种方法可以将它“分配”给一个变量并同时传递 arguments 。


这确实会改变代码的结构,但您也许可以使用yield而不是return

just_a_variable = enumerator(["apple", "banana", "lemon"])正在调用 function enumerator 从技术上讲,这就是enumerator器后面的括号所做的。

也许您注意到,只要运行该文件,就会运行该行(并调用enumerator )。 作为脚本语言,这就是 Python 的工作方式(与 Java 或其他编译语言相比)。

暂无
暂无

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

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