如果函数没有被调用,为什么要从函数中执行 print 语句?
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 语句更改为“return”,它突然无法编译,这就是我仅使用 print 所期望的。我在这里错过了什么吗?
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?)
I assume this is happening because there is a print statement in the function but it still doesn't make sense. if I change the print statement to "return" it suddenly doesn't compile, that is what I was expecting from just using print. I'm I missing something here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一般来说,如果您在函数后面添加括号(如下面的两个示例之一),则会调用该函数。
如果你只是想让一个变量指向一个函数:
那么下面的两个语句将变得相同:
话虽如此,这对我来说似乎有点无用。按照目前的方式定义函数,我不知道如何将其“分配”给变量并同时传递参数。
这确实会改变代码的结构,但您也许可以使用
yield
而不是返回
。In general if you add parenthesis after a function (like one of the two examples below), it is called.
If you just want a variable to point to a function:
Then the following two statements will become identical:
Having said so, this seems a bit useless to me. With you function defined the way it currently is, there isn't a way I know to "assign" it to a variable and pass arguments at the same time.
This does change the structure of your code, but you can perhaps use
yield
instead ofreturn
.just_a_variable = enumerator(["apple", "banana", "lemon"])
行正在调用函数enumerator
。从技术上讲,这就是enumerator
后面的括号的作用。也许您注意到,简单地运行该文件就是运行该行(并调用
enumerator
)。作为一种脚本语言,Python 就是这样工作的(与 Java 或其他编译语言相反)。The line
just_a_variable = enumerator(["apple", "banana", "lemon"])
is calling functionenumerator
. Technically, that is what the parenthesis afterenumerator
do.Perhaps you noticed that simply running the file is running that line (and calling
enumerator
). As a scripting language, this is how Python works (in contrast to Java or other compiled languages).