Python如何从函数返回多个值?

时间:2023-02-03 02:02:56

I have written the following code:

我写了以下代码:

class FigureOut:
   def setName(self, name):
      fullname = name.split()
      self.first_name = fullname[0]
      self.last_name = fullname[1]

   def getName(self):
      return self.first_name, self.last_name

f = FigureOut()
f.setName("Allen Solly")
name = f.getName()
print (name)

I get the following Output:

我得到以下输出:

('Allen', 'Solly')

Whenever multiple values are returned from a function in python, does it always convert the multiple values to a list of multiple values and then returns it from the function?

每当从python中的函数返回多个值时,它是否总是将多个值转换为多个值的列表,然后从函数返回它?

Is the whole process same as converting the multiple values to a list explicitly and then returning the list, for example in JAVA, as one can return only one object from a function in JAVA?

整个过程是否与将多个值显式转换为列表然后返回列表(例如在JAVA中)相同,因为只能从JAVA中的函数返回一个对象?

6 个解决方案

#1


26  

Since the return statement in getName specifies multiple elements:

由于getName中的return语句指定了多个元素:

def getName(self):
   return self.first_name, self.last_name

Python will return a container object that basically contains them.

Python将返回一个基本上包含它们的容器对象。

In this case, returning a comma separated set of elements creates a tuple. Multiple values can only be returned inside containers.

在这种情况下,返回逗号分隔的元素集会创建一个元组。多个值只能在容器内返回。

Let's use a simpler function that returns multiple values:

让我们使用一个返回多个值的简单函数:

def foo(a, b):
    return a, b

You can look at the byte code generated by using dis.dis, a disassembler for Python bytecode. For comma separated values w/o any brackets, it looks like this:

您可以查看使用dis.dis生成的字节代码,它是Python字节码的反汇编程序。对于没有任何括号的逗号分隔值,它看起来像这样:

>>> import dis
>>> def foo(a, b):
...     return a,b        
>>> dis.dis(foo)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 BUILD_TUPLE              2
              9 RETURN_VALUE

As you can see the values are first loaded on the internal stack with LOAD_FAST and then a BUILD_TUPLE (grabbing the previous 2 elements placed on the stack) is generated. Python knows to create a tuple due to the commas being present.

如您所见,首先使用LOAD_FAST将值加载到内部堆栈上,然后生成BUILD_TUPLE(抓取堆栈上的前两个元素)。由于存在逗号,Python知道创建一个元组。

You could alternatively specify another return type, for example a list, by using []. For this case, a BUILD_LIST is going to be issued following the same semantics as it's tuple equivalent:

您也可以使用[]指定另一种返回类型,例如列表。对于这种情况,将按照与元组等效的相同语义发出BUILD_LIST:

>>> def foo_list(a, b):
...     return [a, b]
>>> dis.dis(foo_list)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 BUILD_LIST               2
              9 RETURN_VALUE

The type of object returned really depends on the presence of brackets (for tuples () can be omitted if there's at least one comma). [] creates lists and {} sets. Dictionaries need key:val pairs.

返回的对象类型实际上取决于括号的存在(如果至少有一个逗号,则可以省略元组())。 []创建列表和{}集。字典需要键:val对。

To summarize, one actual object is returned. If that object is of a container type, it can contain multiple values giving the impression of multiple results returned. The usual method then is to unpack them directly:

总而言之,返回一个实际对象。如果该对象属于容器类型,则它可以包含多个值,从而给出返回多个结果的印象。通常的方法是直接解压缩它们:

>>> first_name, last_name = f.getName()
>>> print (first_name, last_name)

As an aside to all this, your Java ways are leaking into Python :-)

除此之外,你的Java方式正在渗入Python :-)

Don't use getters when writing classes in Python, use properties. Properties are the idiomatic way to manage attributes, for more on these, see a nice answer here.

在Python中编写类时,不要使用getter,使用属性。属性是管理属性的惯用方法,有关这些的更多信息,请参阅此处的一个很好的答案。

#2


17  

From Python Cookbook v.30

来自Python Cookbook v.30

def myfun():
    return 1, 2, 3

a, b, c = myfun()

Although it looks like myfun() returns multiple values, a tuple is actually being created. It looks a bit peculiar, but it’s actually the comma that forms a tuple, not the parentheses

虽然看起来myfun()返回多个值,但实际上正在创建一个元组。它看起来有点特殊,但它实际上是形成元组的逗号,而不是括号

So yes, what's going on in Python is an internal transformation from multiple comma separated values to a tuple and vice-versa.

所以,是的,Python中发生的是从多个逗号分隔值到元组的内部转换,反之亦然。

Though there's no equivalent in you can easily create this behaviour using array's or some Collections like Lists:

虽然java中没有等效的东西,但您可以使用数组或列表之类的集合轻松创建此行为:

private static int[] sumAndRest(int x, int y) {
    int[] toReturn = new int[2];

    toReturn[0] = x + y;
    toReturn[1] = x - y;

    return toReturn;

}

Executed in this way:

以这种方式执行:

public static void main(String[] args) {
    int[] results = sumAndRest(10, 5);

    int sum  = results[0];
    int rest = results[1];

    System.out.println("sum = " + sum + "\nrest = " + rest);

}

result:

结果:

sum = 15
rest = 5

#3


6  

Here It is actually returning tuple.

这里实际上是返回元组。

If you execute this code in Python 3:

如果您在Python 3中执行此代码:

def get():
    a = 3
    b = 5
    return a,b
number = get()
print(type(number))
print(number)

Output :

输出:

<class 'tuple'>
(3, 5)

But if you change the code line return [a,b] instead of return a,b and execute :

但是如果你改变代码行返回[a,b]而不是返回a,b并执行:

def get():
    a = 3
    b = 5
    return [a,b]
number = get()
print(type(number))
print(number)

Output :

输出:

<class 'list'>
[3, 5]

It is only returning single object which contains multiple values.

它只返回包含多个值的单个对象。

There is another alternative to return statement for returning multiple values, use yield( to check in details see this What does the "yield" keyword do in Python?)

还有另一种返回语句用于返回多个值,使用yield(详细信息请参阅“yield”关键字在Python中的作用是什么?)

Sample Example :

示例示例:

def get():
    for i in range(5):
        yield i
number = get()
print(type(number))
print(number)
for i in number:
    print(i)

Output :

输出:

<class 'generator'>
<generator object get at 0x7fbe5a1698b8>
0
1
2
3
4

#4


3  

Python functions always return a unique value. The comma operator is the constructor of tuples so self.first_name, self.last_name evaluates to a tuple and that tuple is the actual value the function is returning.

Python函数始终返回唯一值。逗号运算符是元组的构造函数,因此self.first_name,self.last_name计算为元组,该元组是函数返回的实际值。

#5


2  

Whenever multiple values are returned from a function in python, does it always convert the multiple values to a list of multiple values and then returns it from the function??

每当从python中的函数返回多个值时,它是否总是将多个值转换为多个值的列表,然后从函数中返回它?

I'm just adding a name and print the result that returns from the function. the type of result is 'tuple'.

我只是添加一个名称并打印从函数返回的结果。结果的类型是'元组'。

  class FigureOut:
   first_name = None
   last_name = None
   def setName(self, name):
      fullname = name.split()
      self.first_name = fullname[0]
      self.last_name = fullname[1]
      self.special_name = fullname[2]
   def getName(self):
      return self.first_name, self.last_name, self.special_name

f = FigureOut()
f.setName("Allen Solly Jun")
name = f.getName()
print type(name)


I don't know whether you have heard about 'first class function'. Python is the language that has 'first class function'

我不知道你是否听说过“头等舱功能”。 Python是具有“一流功能”的语言

I hope my answer could help you. Happy coding.

我希望我的回答可以帮到你。快乐的编码。

#6


0  

mentioned also here, you can use this:

这里也提到过,你可以用这个:

import collections
Point = collections.namedtuple('Point', ['x', 'y'])
p = Point(1, y=2)
>>> p.x, p.y
1 2
>>> p[0], p[1]
1 2

#1


26  

Since the return statement in getName specifies multiple elements:

由于getName中的return语句指定了多个元素:

def getName(self):
   return self.first_name, self.last_name

Python will return a container object that basically contains them.

Python将返回一个基本上包含它们的容器对象。

In this case, returning a comma separated set of elements creates a tuple. Multiple values can only be returned inside containers.

在这种情况下,返回逗号分隔的元素集会创建一个元组。多个值只能在容器内返回。

Let's use a simpler function that returns multiple values:

让我们使用一个返回多个值的简单函数:

def foo(a, b):
    return a, b

You can look at the byte code generated by using dis.dis, a disassembler for Python bytecode. For comma separated values w/o any brackets, it looks like this:

您可以查看使用dis.dis生成的字节代码,它是Python字节码的反汇编程序。对于没有任何括号的逗号分隔值,它看起来像这样:

>>> import dis
>>> def foo(a, b):
...     return a,b        
>>> dis.dis(foo)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 BUILD_TUPLE              2
              9 RETURN_VALUE

As you can see the values are first loaded on the internal stack with LOAD_FAST and then a BUILD_TUPLE (grabbing the previous 2 elements placed on the stack) is generated. Python knows to create a tuple due to the commas being present.

如您所见,首先使用LOAD_FAST将值加载到内部堆栈上,然后生成BUILD_TUPLE(抓取堆栈上的前两个元素)。由于存在逗号,Python知道创建一个元组。

You could alternatively specify another return type, for example a list, by using []. For this case, a BUILD_LIST is going to be issued following the same semantics as it's tuple equivalent:

您也可以使用[]指定另一种返回类型,例如列表。对于这种情况,将按照与元组等效的相同语义发出BUILD_LIST:

>>> def foo_list(a, b):
...     return [a, b]
>>> dis.dis(foo_list)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 BUILD_LIST               2
              9 RETURN_VALUE

The type of object returned really depends on the presence of brackets (for tuples () can be omitted if there's at least one comma). [] creates lists and {} sets. Dictionaries need key:val pairs.

返回的对象类型实际上取决于括号的存在(如果至少有一个逗号,则可以省略元组())。 []创建列表和{}集。字典需要键:val对。

To summarize, one actual object is returned. If that object is of a container type, it can contain multiple values giving the impression of multiple results returned. The usual method then is to unpack them directly:

总而言之,返回一个实际对象。如果该对象属于容器类型,则它可以包含多个值,从而给出返回多个结果的印象。通常的方法是直接解压缩它们:

>>> first_name, last_name = f.getName()
>>> print (first_name, last_name)

As an aside to all this, your Java ways are leaking into Python :-)

除此之外,你的Java方式正在渗入Python :-)

Don't use getters when writing classes in Python, use properties. Properties are the idiomatic way to manage attributes, for more on these, see a nice answer here.

在Python中编写类时,不要使用getter,使用属性。属性是管理属性的惯用方法,有关这些的更多信息,请参阅此处的一个很好的答案。

#2


17  

From Python Cookbook v.30

来自Python Cookbook v.30

def myfun():
    return 1, 2, 3

a, b, c = myfun()

Although it looks like myfun() returns multiple values, a tuple is actually being created. It looks a bit peculiar, but it’s actually the comma that forms a tuple, not the parentheses

虽然看起来myfun()返回多个值,但实际上正在创建一个元组。它看起来有点特殊,但它实际上是形成元组的逗号,而不是括号

So yes, what's going on in Python is an internal transformation from multiple comma separated values to a tuple and vice-versa.

所以,是的,Python中发生的是从多个逗号分隔值到元组的内部转换,反之亦然。

Though there's no equivalent in you can easily create this behaviour using array's or some Collections like Lists:

虽然java中没有等效的东西,但您可以使用数组或列表之类的集合轻松创建此行为:

private static int[] sumAndRest(int x, int y) {
    int[] toReturn = new int[2];

    toReturn[0] = x + y;
    toReturn[1] = x - y;

    return toReturn;

}

Executed in this way:

以这种方式执行:

public static void main(String[] args) {
    int[] results = sumAndRest(10, 5);

    int sum  = results[0];
    int rest = results[1];

    System.out.println("sum = " + sum + "\nrest = " + rest);

}

result:

结果:

sum = 15
rest = 5

#3


6  

Here It is actually returning tuple.

这里实际上是返回元组。

If you execute this code in Python 3:

如果您在Python 3中执行此代码:

def get():
    a = 3
    b = 5
    return a,b
number = get()
print(type(number))
print(number)

Output :

输出:

<class 'tuple'>
(3, 5)

But if you change the code line return [a,b] instead of return a,b and execute :

但是如果你改变代码行返回[a,b]而不是返回a,b并执行:

def get():
    a = 3
    b = 5
    return [a,b]
number = get()
print(type(number))
print(number)

Output :

输出:

<class 'list'>
[3, 5]

It is only returning single object which contains multiple values.

它只返回包含多个值的单个对象。

There is another alternative to return statement for returning multiple values, use yield( to check in details see this What does the "yield" keyword do in Python?)

还有另一种返回语句用于返回多个值,使用yield(详细信息请参阅“yield”关键字在Python中的作用是什么?)

Sample Example :

示例示例:

def get():
    for i in range(5):
        yield i
number = get()
print(type(number))
print(number)
for i in number:
    print(i)

Output :

输出:

<class 'generator'>
<generator object get at 0x7fbe5a1698b8>
0
1
2
3
4

#4


3  

Python functions always return a unique value. The comma operator is the constructor of tuples so self.first_name, self.last_name evaluates to a tuple and that tuple is the actual value the function is returning.

Python函数始终返回唯一值。逗号运算符是元组的构造函数,因此self.first_name,self.last_name计算为元组,该元组是函数返回的实际值。

#5


2  

Whenever multiple values are returned from a function in python, does it always convert the multiple values to a list of multiple values and then returns it from the function??

每当从python中的函数返回多个值时,它是否总是将多个值转换为多个值的列表,然后从函数中返回它?

I'm just adding a name and print the result that returns from the function. the type of result is 'tuple'.

我只是添加一个名称并打印从函数返回的结果。结果的类型是'元组'。

  class FigureOut:
   first_name = None
   last_name = None
   def setName(self, name):
      fullname = name.split()
      self.first_name = fullname[0]
      self.last_name = fullname[1]
      self.special_name = fullname[2]
   def getName(self):
      return self.first_name, self.last_name, self.special_name

f = FigureOut()
f.setName("Allen Solly Jun")
name = f.getName()
print type(name)


I don't know whether you have heard about 'first class function'. Python is the language that has 'first class function'

我不知道你是否听说过“头等舱功能”。 Python是具有“一流功能”的语言

I hope my answer could help you. Happy coding.

我希望我的回答可以帮到你。快乐的编码。

#6


0  

mentioned also here, you can use this:

这里也提到过,你可以用这个:

import collections
Point = collections.namedtuple('Point', ['x', 'y'])
p = Point(1, y=2)
>>> p.x, p.y
1 2
>>> p[0], p[1]
1 2