返回函数的输出与打印它有何不同?

2024-04-25 16:31:46 发布

您现在位置:Python中文网/ 问答频道 /正文

在我之前的question中,Andrew Jaffe写道:

In addition to all of the other hints and tips, I think you're missing something crucial: your functions actually need to return something. When you create autoparts() or splittext(), the idea is that this will be a function that you can call, and it can (and should) give something back. Once you figure out the output that you want your function to have, you need to put it in a return statement.

def autoparts():
    parts_dict = {}
    list_of_parts = open('list_of_parts.txt', 'r')

    for line in list_of_parts:
        k, v = line.split()
        parts_dict[k] = v

    print(parts_dict)

>>> autoparts()
{'part A': 1, 'part B': 2, ...}

此函数创建字典,但不返回任何内容。但是,由于我添加了print,因此在运行函数时会显示函数的输出。做某事和做某事有什么区别?


Tags: andoftheto函数youyourreturn
3条回答

我认为您很困惑,因为您是从REPL运行的,它会在您调用函数时自动打印出返回的值。在这种情况下,无论您有一个函数来创建一个值、打印它并将其丢弃,还是有一个函数来创建一个值并返回它,让REPL打印它,都会得到相同的输出。

然而,这些都不是同一件事,当您使用另一个函数调用autoparts时,您会意识到,该函数希望使用autoparts创建的值执行某些操作。

print语句将向用户输出一个对象。一旦函数完成,return语句将允许将字典分配给变量

>>> def foo():
...     print "Hello, world!"
... 
>>> a = foo()
Hello, world!
>>> a
>>> def foo():
...     return "Hello, world!"
... 
>>> a = foo()
>>> a
'Hello, world!'

或者在返回字典的上下文中:

>>> def foo():
...     print {'a' : 1, 'b' : 2}
... 
>>> a = foo()
{'a': 1, 'b': 2}
>>> a
>>> def foo():
...     return {'a' : 1, 'b' : 2}
... 
>>> a = foo()
>>> a
{'a': 1, 'b': 2}

(执行一行之后不输出任何内容的语句是指最后一个返回的语句None)

Print只是将结构打印到输出设备(通常是控制台)。没别的了。要从函数中返回它,请执行以下操作:

def autoparts():
  parts_dict = {}
  list_of_parts = open('list_of_parts.txt', 'r')
  for line in list_of_parts:
        k, v = line.split()
        parts_dict[k] = v
  return parts_dict

为什么回来?如果你不这样做,字典就会死掉(被垃圾收集),一旦这个函数调用结束就不能再访问了。如果你返回值,你可以用它做其他事情。例如:

my_auto_parts = autoparts() 
print(my_auto_parts['engine']) 

看到了吗?调用了auto parts(),它返回parts_dict,并将其存储到my_auto_parts变量中。现在我们可以使用这个变量来访问dictionary对象,即使函数调用已经结束,它仍然继续存在。然后我们用“引擎”键在字典里打印出这个对象。

要获得一个好的教程,请查看dive into python。它是免费的,很容易跟踪。

相关问题 更多 >