如果函数未被调用,为什么要从函数执行打印语句


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?)

我认为发生这种情况是因为函数中有一个print语句,但它仍然没有意义。如果我将打印语句更改为";返回";它突然无法编译,这正是我对使用print的期望。我是不是错过了什么?

通常,如果在函数后面添加括号(如下面两个示例之一(,就会调用它。

function_name(arguments)
variable = function_name(arguments)

如果你只想让一个变量指向一个函数:

variable = function

然后以下两个语句将变得相同:

variable(arguments)
function(arguments)

话虽如此,这对我来说似乎有点无用。按照你目前的方式定义函数,我不知道有什么方法可以";分配";它传递给一个变量,同时传递参数。


这确实会更改代码的结构,但您可能会使用yield而不是return

just_a_variable = enumerator(["apple", "banana", "lemon"])调用函数enumerator。从技术上讲,enumerator后面的括号就是这样做的

也许您注意到,简单地运行文件就是运行那一行(并调用enumerator(。作为一种脚本语言,Python就是这样工作的(与Java或其他编译语言不同(。

最新更新