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

How does Python return multiple values from a function?(Python如何从一个函数返回多个值?)
本文介绍了Python如何从一个函数返回多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下代码:

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)

我得到以下输出:

('Allen', 'Solly')

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

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?

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

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?

推荐答案

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

Since the return statement in getName specifies multiple elements:

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

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

Python will return a container object that basically contains them.

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

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

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

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:

>>> 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

如您所见,这些值首先使用 LOAD_FAST 加载到内部堆栈,然后是 BUILD_TUPLE(抓取之前放置在堆栈上的2 个元素).由于存在逗号,Python 知道创建一个元组.

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.

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

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:

>>> 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

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

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.

总而言之,返回一个实际对象.如果该对象是容器类型,它可以包含多个值,给人以返回多个结果的印象.然后通常的方法是直接解包:

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)

<小时>

除此之外,您的 Java 方法正在泄漏到 Python 中:-)


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

在 Python 中编写类时不要使用 getter,使用 properties.属性是管理属性的惯用方式,有关这些的更多信息,请参阅一个不错的答案 这里.

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如何从一个函数返回多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)