如果函数没有被调用,为什么要从函数中执行 print 语句?

发布于 2025-01-11 01:11:52 字数 502 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风和你 2025-01-18 01:11:52

一般来说,如果您在函数后面添加括号(如下面的两个示例之一),则会调用该函数。

function_name(arguments)
variable = function_name(arguments)

 

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

variable = function

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

variable(arguments)
function(arguments)

话虽如此,这对我来说似乎有点无用。按照目前的方式定义函数,我不知道如何将其“分配”给变量并同时传递参数。


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

In general if you add parenthesis after a function (like one of the two examples below), it is called.

function_name(arguments)
variable = function_name(arguments)

If you just want a variable to point to a function:

variable = function

Then the following two statements will become identical:

variable(arguments)
function(arguments)

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 of return.

待"谢繁草 2025-01-18 01:11:52

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

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

The line just_a_variable = enumerator(["apple", "banana", "lemon"]) is calling function enumerator. Technically, that is what the parenthesis after enumerator 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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文