一个函数可以返回多少个值?

How many values can be returned from a function?

在 python 你可以这样做:

def myFunction():
    return "String", 5.5, True, 11

val1, val2, val3, val4 = myFunction()

我认为这是一个 returns 4 个值的函数,但是我的 python 老师说我错了,这只是 returns 一个元组。

我个人认为这是一个没有区别的区别,因为没有迹象表明这四个值被转换成一个元组然后解构为4个值。我不知道这与 JavaScript.

等语言中的相同类型的构造有何不同

我说得对吗?

您的导师是正确的。

https://docs.python.org/3/reference/datamodel.html#objects-values-and-types

Tuples

The items of a tuple are arbitrary Python objects. Tuples of two or more items are formed by comma-separated lists of expressions. A tuple of one item (a ‘singleton’) can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). An empty tuple can be formed by an empty pair of parentheses.

应用于您的示例:

foo = "String", 5.5, True, 11
assert isinstance(foo, tuple)

所以你显然返回了一个对象。

当有多个目标(左侧的变量)时,赋值表达式的指定方式如下:

https://docs.python.org/3/reference/simple_stmts.html#assignment-statements

Assignment of an object to a target list, optionally enclosed in parentheses or square brackets, is recursively defined as follows.

If the target list is a single target with no trailing comma, optionally in parentheses, the object is assigned to that target.

Else: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

(全部强调我的)

我会尝试一下,因为我认为这里的问题是缺乏正确定义术语。完全迂腐地说,问题的正确答案是“零”。 Python 没有 return 值;它 return 是一个对象,对象与值不是一回事。回到基础知识:

https://docs.python.org/3/reference/datamodel.html#objects-values-and-types

Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects.

还有:

Every object has an identity, a type and a value.

如上所述,值与对象不同。函数 return objects 而不是 values,所以问题的答案(如所问,如果采取极端的文字)是零。如果问题是“这个函数将 return 多少对象发送给调用者?”那么答案就是一个。这就是为什么定义术语很重要,以及为什么模糊的问题会产生多个(可能是正确的)答案。从另一种意义上说,这个问题的正确答案应该是五个,因为有五个东西可能会被认为是从这个函数返回的“值”。有一个元组,元组中有四个项目。从另一种意义上说,答案是四个(如您所说),因为代码完全显示 return 然后有四个值。

所以真的,你们都对,你们都错了,但这只是因为这个问题对于它想知道的内容还不够清楚。讲师可能试图提出 Python return 单个对象的想法,其中可能包含多个其他对象。了解这一点很重要,因为它有助于 Python 在传递数据时的灵活性。我不太确定讲师的措辞方式是否实现了该目标,但我也没有出现在 class 中,所以很难说。理想情况下,教学应该涵盖神经多样性的理解方式,但我会把那个肥皂盒留到另一个讨论中。

让我们像这样提炼一下,希望能提供一个清晰的总结。 Python 没有 return 值,它 return 是对象。为此,一个函数只能return一个对象。该对象可以包含多个值,甚至可以引用其他对象,因此虽然您的函数可以将多个值传回给调用者,但它必须在单个对象内部这样做。 “对象”是 Python 内部数据的内部单位,与对象中包含的“值”截然不同,因此在 Python 中始终牢记两者之间的区别是一个很好的做法两者及其使用方式,无论问题的措辞如何。