如何从函数返回多个值?

时间:2022-02-01 22:36:38

The canonical way to return multiple values in languages that support it is often tupling.

在支持它的语言中返回多个值的规范方法通常是tupling。

Option: Using a tuple

Consider this trivial example:

考虑这个简单的例子:

def f(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return (y0,y1,y2)

However, this quickly gets problematic as the number of values returned increases. What if you want to return four or five values? Sure, you could keep tupling them, but it gets easy to forget which value is where. It's also rather ugly to unpack them wherever you want to receive them.

但是,随着返回值的增加,这很快就会出现问题。如果您想要返回四个或五个值,该怎么办?当然,你可以保持它们的组合,但很容易忘记哪个值在哪里。在任何想要接收它们的地方解压缩它们也是相当丑陋的。

Option: Using a dictionary

The next logical step seems to be to introduce some sort of 'record notation'. In python, the obvious way to do this is by means of a dict.

下一个合乎逻辑的步骤似乎是引入某种“记录符号”。在python中,显而易见的方法是通过dict。

Consider the following:

考虑以下:

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0':y0, 'y1':y1 ,'y2':y2 }

(edit- Just to be clear, y0, y1 and y2 are just meant as abstract identifiers. As pointed out, in practice you'd use meaningful identifiers)

(编辑 - 只是要清楚,y0,y1和y2只是作为抽象标识符。正如所指出的,在实践中你会使用有意义的标识符)

Now, we have a mechanism whereby we can project out a particular member of the returned object. For example,

现在,我们有一个机制,我们可以通过这种机制投出返回对象的特定成员。例如,

result['y0']

Option: Using a class

However, there is another option. We could instead return a specialized structure. I've framed this in the context of Python, but I'm sure it applies to other languages as well. Indeed, if you were working in C this might very well be your only option. Here goes:

但是,还有另一种选择。我们可以返回一个专门的结构。我已经在Python的上下文中对此进行了构建,但我确信它也适用于其他语言。事实上,如果你在C工作,这可能是你唯一的选择。开始:

class ReturnValue(object):
  def __init__(self, y0, y1, y2):
     self.y0 = y0
     self.y1 = y1
     self.y2 = y2

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return ReturnValue(y0, y1, y2)

In python the previous two are perhaps very similar in terms of plumbing- After all { y0, y1, y2 } just end up being entries in the internal __dict__ of the ReturnValue.

在python中,前两个在管道方面可能非常相似 - 毕竟{y0,y1,y2}最终只是ReturnValue内部__dict__中的条目。

There is one additional feature provided by Python though for tiny objects, the __slots__ attribute. The class could be expressed as:

Python提供了一个额外的功能,但是对于微小的对象__slots__属性。该课程可表达为:

class ReturnValue(object):
  __slots__ = ["y0", "y1", "y2"]
  def __init__(self, y0, y1, y2):
     self.y0 = y0
     self.y1 = y1
     self.y2 = y2

From the Python Reference Manual:

从Python参考手册:

The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because __dict__ is not created for each instance.

__slots__声明采用一系列实例变量,并在每个实例中保留足够的空间来保存每个变量的值。保存空间是因为没有为每个实例创建__dict__。

Option: Using a list

Another suggestion which I'd overlooked comes from Bill the Lizard:

我忽略的另一个建议来自比尔蜥蜴:

def h(x):
  result = [x + 1]
  result.append(x * 3)
  result.append(y0 ** y3)
  return result

This is my least favorite method though. I suppose I'm tainted by exposure to Haskell, but the idea of mixed-type lists has always felt uncomfortable to me. In this particular example the list is -not- mixed type, but it conceivably could be. A list used in this way really doesn't gain anything with respect to the tuple as far as I can tell. The only real difference between lists and tuples in Python is that lists are mutable, wheras tuples are not. I personally tend to carry over the conventions from functional programming: use lists for any number of elements of the same type, and tuples for a fixed number of elements of predetermined types.

这是我最不喜欢的方法。我想我已经被Haskell暴露了,但混合型列表的想法一直让我觉得不舒服。在这个特定的例子中,列表是-not-混合类型,但可以想象它可以。就我所知,以这种方式使用的列表实际上并没有获得关于元组的任何信息。 Python中列表和元组之间唯一真正的区别是列表是可变的,而元组则不是。我个人倾向于从函数式编程中继承惯例:对任何数量的相同类型的元素使用列表,对于预定类型的固定数量的元素使用元组。

Question

After the lengthy preamble, comes the inevitable question. Which method (do you think) is best?

在冗长的序言之后,出现了不可避免的问题。你觉得哪种方法最好?

I've typically found myself going the dictionary route because it involves less set-up work. From a types perspective however, you might be better off going the class route, since that may help you avoid confusing what a dictionary represents. On the other hand, there are some in the Python community that feel implied interfaces should be preferred to explicit interfaces, at which point the type of the object really isn't relevant, since you're basically relying on the convention that the same attribute will always have the same meaning.

我通常发现自己去了字典路线,因为它涉及较少的设置工作。但是从类型的角度来看,你可能会更好地走上课程路线,因为这可以帮助你避免混淆字典所代表的内容。另一方面,Python社区中有一些人认为隐含接口应该优先于显式接口,此时对象的类型确实不相关,因为您基本上依赖于相同属性的约定将永远具有相同的含义。

So, how do -you- return multiple values in Python?

那么,你如何在Python中返回多个值?

14 个解决方案

#1


552  

Named tuples were added in 2.6 for this purpose. Also see os.stat for a similar builtin example.

为此目的,在2.6中添加了命名元组。另请参阅os.stat以获取类似的内置示例。

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

In recent versions of Python 3 (3.6+, I think), the new typing library got the NamedTuple class to make named tuples easier to create and more powerful. Inheriting from typing.NamedTuple lets you use docstrings, default values, and type annotations.

在Python 3的最新版本(3.6+,我认为)中,新的类型库得到了NamedTuple类,使命名元组更容易创建,功能更强大。继承自键入.NamedTuple允许您使用文档字符串,默认值和类型注释。

Example (From the docs):

示例(来自文档):

class Employee(NamedTuple):  # inherit from collections.NamedTuple
    name: str
    id: int = 3  # default value

employee = Employee('Guido')
assert employee.id == 3

#2


180  

For small projects I find it easiest to work with tuples. When that gets too hard to manage (and not before) I start grouping things into logical structures, however I think your suggested use of dictionaries and ReturnValue objects is wrong (or too simplistic).

对于小项目,我发现使用元组最容易。当它变得难以管理(而不是之前)时,我开始将事物分组为逻辑结构,但是我认为你建议使用字典和ReturnValue对象是错误的(或过于简单化)。

Returning a dictionary with keys y0, y1, y2 etc doesn't offer any advantage over tuples. Returning a ReturnValue instance with properties .y0 .y1 .y2 etc doesn't offer any advantage over tuples either. You need to start naming things if you want to get anywhere, and you can do that using tuples anyway:

返回带有键y0,y1,y2等的字典并不比元组提供任何优势。返回具有属性.y0 .y1 .y2等的ReturnValue实例也不会提供任何优于元组的优势。如果你想要到达任何地方,你需要开始命名,你可以使用元组来做到这一点:

def getImageData(filename):
  [snip]
  return size, (format, version, compression), (width,height)
size, type, dimensions = getImageData(x)

IMHO, the only good technique beyond tuples is to return real objects with proper methods and properties, like you get from re.match() or open(file).

恕我直言,超越元组的唯一好方法是返回具有适当方法和属性的真实对象,就像从re.match()或open(文件)获得的那样。

#3


149  

A lot of the answers suggest you need to return a collection of some sort, like a dictionary or a list. You could leave off the extra syntax and just write out the return values, comma-separated. Note: this technically returns a tuple.

很多答案都表明你需要返回某种类型的集合,比如字典或列表。你可以省去额外的语法,然后写出以逗号分隔的返回值。注意:这在技术上返回一个元组。

def f():
    return True, False
x, y = f()
print(x)
print(y)

gives:

True
False

#4


62  

I vote for the dictionary.

我投票给字典。

I find that if I make a function that returns anything more than 2-3 variables I'll fold them up in a dictionary. Otherwise I tend to forget the order and content of what I'm returning.

我发现如果我创建一个返回超过2-3个变量的函数,我会将它们折叠起来放在字典中。否则我倾向于忘记我正在返回的顺序和内容。

Also, introducing a 'special' structure makes your code more difficult to follow. (Someone else will have to search through the code to find out what it is)

此外,引入“特殊”结构会使您的代码更难以遵循。 (其他人将不得不搜索代码以找出它是什么)

If your concerned about type look up, use descriptive dictionary keys, for example, 'x-values list'.

如果您关注类型查找,请使用描述性字典键,例如“x-values list”。

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0':y0, 'y1':y1 ,'y2':y2 }

#5


33  

Another option would be using generators:

另一种选择是使用发电机:

>>> def f(x):
        y0 = x + 1
        yield y0
        yield x * 3
        yield y0 ** 4


>>> a, b, c = f(5)
>>> a
6
>>> b
15
>>> c
1296

Although IMHO tuples are usually best, except in cases where the values being returned are candidates for encapsulation in a class.

虽然IMHO元组通常是最好的,除非返回的值是类中封装的候选者。

#6


25  

I prefer to use tuples whenever a tuple feels "natural"; coordinates are a typical example, where the separate objects can stand on their own, e.g. in one-axis only scaling calculations, and the order is important. Note: if I can sort or shuffle the items without an adverse effect to the meaning of the group, then I probably shouldn't use a tuple.

每当元组感觉“自然”时,我更喜欢使用元组;坐标是一个典型的例子,其中单独的对象可以独立存在,例如,在单轴仅缩放计算中,顺序很重要。注意:如果我可以对项目进行排序或改组而不会对组的含义产生负面影响,那么我可能不应该使用元组。

I use dictionaries as a return value only when the grouped objects aren't always the same. Think optional email headers.

仅当分组对象不总是相同时,才使用字典作为返回值。想想可选的邮箱标题。

For the rest of the cases, where the grouped objects have inherent meaning inside the group or a fully-fledged object with its own methods is needed, I use a class.

对于其他情况,如果分组对象在组内部具有固有含义,或者需要具有自己方法的完全成熟对象,则使用类。

#7


22  

I prefer

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0':y0, 'y1':y1 ,'y2':y2 }

it seems everything else is just extra code to do the same thing.

似乎其他一切只是额外的代码来做同样的事情。

#8


22  

>>> def func():
...    return [1,2,3]
...
>>> a,b,c = func()
>>> a
1
>>> b
2
>>> c
3

#9


16  

Python's tuples, dicts, and objects offer the programmer a smooth tradeoff between formality and convenience for small data structures ("things"). For me, the choice of how to represent a thing is dictated mainly by how I'm going to use the structure. In C++, it's a common convention to use struct for data-only items and class for objects with methods, even though you can legally put methods on a struct; my habit is similar in Python, with dict and tuple in place of struct.

Python的元组,dicts和对象为程序员提供了在小型数据结构(“事物”)的形式和便利之间的平滑权衡。对我来说,如何表示事物的选择主要取决于我将如何使用该结构。在C ++中,将结构用于仅数据项和使用方法的对象是一种常见的约定,即使您可以合法地将方法放在结构上;我的习惯在Python中类似,用dict和tuple代替struct。

For coordinate sets, I'll use a tuple rather than a point class or a dict (and note that you can use a tuple as a dictionary key, so dicts make great sparse multidimensional arrays).

对于坐标集,我将使用元组而不是点类或dict(并注意您可以使用元组作为字典键,因此dicts可以生成非常稀疏的多维数组)。

If I'm going to be iterating over a list of things, I prefer unpacking tuples on the iteration:

如果我要迭代一系列事物,我更喜欢在迭代中解包元组:

for score,id,name in scoreAllTheThings():
    if score > goodScoreThreshold:
        print "%6.3f #%6d %s"%(score,id,name)

...as the object version is more cluttered to read:

...因为对象版本更杂乱阅读:

for entry in scoreAllTheThings():
    if entry.score > goodScoreThreshold:
        print "%6.3f #%6d %s"%(entry.score,entry.id,entry.name)

...let alone the dict.

......更别说这个词了。

for entry in scoreAllTheThings():
    if entry['score'] > goodScoreThreshold:
        print "%6.3f #%6d %s"%(entry['score'],entry['id'],entry['name'])

If the thing is widely used, and you find yourself doing similar non-trivial operations on it in multiple places in the code, then it's usually worthwhile to make it a class object with appropriate methods.

如果事物被广泛使用,并且你发现自己在代码中的多个位置对它进行类似的非平凡操作,那么通常使用适当的方法使它成为一个类对象是值得的。

Finally, if I'm going to be exchanging data with non-Python system components, I'll most often keep them in a dict because that's best suited to JSON serialization.

最后,如果我要与非Python系统组件交换数据,我通常会将它们保存在dict中,因为它最适合JSON序列化。

#10


15  

Generally, the "specialized structure" actually IS a sensible current state of an object, with its own methods.

通常,“专用结构”实际上是对象的合理当前状态,具有其自己的方法。

class Some3SpaceThing(object):
  def __init__(self,x):
    self.g(x)
  def g(self,x):
    self.y0 = x + 1
    self.y1 = x * 3
    self.y2 = y0 ** y3

r = Some3SpaceThing( x )
r.y0
r.y1
r.y2

I like to find names for anonymous structures where possible. Meaningful names make things more clear.

我喜欢在可能的情况下找到匿名结构的名称。有意义的名字使事情变得更加清晰。

#11


14  

+1 on S.Lott's suggestion of a named container class.

关于S.Lott建议使用命名容器类的+1。

For python 2.6 and up, a named tuple provides a useful way of easily creating these container classes, and the results are "lightweight and require no more memory than regular tuples".

对于python 2.6及更高版本,命名元组提供了一种轻松创建这些容器类的有用方法,结果是“轻量级,并且不需要比常规元组更多的内存”。

#12


3  

In languages like Python, I would usually use a dictionary as it involves less overhead than creating a new class.

在像Python这样的语言中,我通常会使用字典,因为它比创建新类所需的开销更少。

However, if I find myself constantly returning the same set of variables, then that probably involves a new class that I'll factor out.

但是,如果我发现自己经常返回相同的变量集,那么这可能涉及一个我将要考虑的新类。

#13


3  

I would use a dict to pass and return values from a function:

我会使用dict来传递和返回函数的值:

Use variable form as defined in form.

使用表单中定义的变量形式。

form = {
    'level': 0,
    'points': 0,
    'game': {
        'name': ''
    }
}


def test(form):
    form['game']['name'] = 'My game!'
    form['level'] = 2

    return form

>>> print(test(form))
{u'game': {u'name': u'My game!'}, u'points': 0, u'level': 2}

This is the most efficient way for me and for processing unit.

这对我和处理单元来说是最有效的方式。

You have to pass just one pointer in and return just one pointer out.

你必须只传入一个指针并返回一个指针。

You do not have to change functions' (thousands of them) arguments whenever you make a change in your code.

无论何时在代码中进行更改,都不必更改函数(数千个)参数。

#14


2  

"Best" is a partially subjective decision. Use tuples for small return sets in the general case where an immutable is acceptable. A tuple is always preferable to a list when mutability is not a requirement.

“最佳”是一个部分主观的决定。在可接受不可变的一般情况下,使用元组作为小返回集。当不需要可变性时,元组总是优于列表。

For more complex return values, or for the case where formality is valuable (i.e. high value code) a named tuple is better. For the most complex case an object is usually best. However, it's really the situation that matters. If it makes sense to return an object because that is what you naturally have at the end of the function (e.g. Factory pattern) then return the object.

对于更复杂的返回值,或者对于形式有价值的情况(即高价值代码),命名元组更好。对于最复杂的情​​况,对象通常是最好的。然而,重要的是情况。如果返回一个对象是有意义的,因为这是你在函数结束时自然拥有的(例如工厂模式)然后返回对象。

As the wise man said:

正如智者所说:

Premature optimization is the root of all evil (or at least most of it) in programming.

过早优化是编程中所有邪恶(或至少大部分)的根源。

#1


552  

Named tuples were added in 2.6 for this purpose. Also see os.stat for a similar builtin example.

为此目的,在2.6中添加了命名元组。另请参阅os.stat以获取类似的内置示例。

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

In recent versions of Python 3 (3.6+, I think), the new typing library got the NamedTuple class to make named tuples easier to create and more powerful. Inheriting from typing.NamedTuple lets you use docstrings, default values, and type annotations.

在Python 3的最新版本(3.6+,我认为)中,新的类型库得到了NamedTuple类,使命名元组更容易创建,功能更强大。继承自键入.NamedTuple允许您使用文档字符串,默认值和类型注释。

Example (From the docs):

示例(来自文档):

class Employee(NamedTuple):  # inherit from collections.NamedTuple
    name: str
    id: int = 3  # default value

employee = Employee('Guido')
assert employee.id == 3

#2


180  

For small projects I find it easiest to work with tuples. When that gets too hard to manage (and not before) I start grouping things into logical structures, however I think your suggested use of dictionaries and ReturnValue objects is wrong (or too simplistic).

对于小项目,我发现使用元组最容易。当它变得难以管理(而不是之前)时,我开始将事物分组为逻辑结构,但是我认为你建议使用字典和ReturnValue对象是错误的(或过于简单化)。

Returning a dictionary with keys y0, y1, y2 etc doesn't offer any advantage over tuples. Returning a ReturnValue instance with properties .y0 .y1 .y2 etc doesn't offer any advantage over tuples either. You need to start naming things if you want to get anywhere, and you can do that using tuples anyway:

返回带有键y0,y1,y2等的字典并不比元组提供任何优势。返回具有属性.y0 .y1 .y2等的ReturnValue实例也不会提供任何优于元组的优势。如果你想要到达任何地方,你需要开始命名,你可以使用元组来做到这一点:

def getImageData(filename):
  [snip]
  return size, (format, version, compression), (width,height)
size, type, dimensions = getImageData(x)

IMHO, the only good technique beyond tuples is to return real objects with proper methods and properties, like you get from re.match() or open(file).

恕我直言,超越元组的唯一好方法是返回具有适当方法和属性的真实对象,就像从re.match()或open(文件)获得的那样。

#3


149  

A lot of the answers suggest you need to return a collection of some sort, like a dictionary or a list. You could leave off the extra syntax and just write out the return values, comma-separated. Note: this technically returns a tuple.

很多答案都表明你需要返回某种类型的集合,比如字典或列表。你可以省去额外的语法,然后写出以逗号分隔的返回值。注意:这在技术上返回一个元组。

def f():
    return True, False
x, y = f()
print(x)
print(y)

gives:

True
False

#4


62  

I vote for the dictionary.

我投票给字典。

I find that if I make a function that returns anything more than 2-3 variables I'll fold them up in a dictionary. Otherwise I tend to forget the order and content of what I'm returning.

我发现如果我创建一个返回超过2-3个变量的函数,我会将它们折叠起来放在字典中。否则我倾向于忘记我正在返回的顺序和内容。

Also, introducing a 'special' structure makes your code more difficult to follow. (Someone else will have to search through the code to find out what it is)

此外,引入“特殊”结构会使您的代码更难以遵循。 (其他人将不得不搜索代码以找出它是什么)

If your concerned about type look up, use descriptive dictionary keys, for example, 'x-values list'.

如果您关注类型查找,请使用描述性字典键,例如“x-values list”。

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0':y0, 'y1':y1 ,'y2':y2 }

#5


33  

Another option would be using generators:

另一种选择是使用发电机:

>>> def f(x):
        y0 = x + 1
        yield y0
        yield x * 3
        yield y0 ** 4


>>> a, b, c = f(5)
>>> a
6
>>> b
15
>>> c
1296

Although IMHO tuples are usually best, except in cases where the values being returned are candidates for encapsulation in a class.

虽然IMHO元组通常是最好的,除非返回的值是类中封装的候选者。

#6


25  

I prefer to use tuples whenever a tuple feels "natural"; coordinates are a typical example, where the separate objects can stand on their own, e.g. in one-axis only scaling calculations, and the order is important. Note: if I can sort or shuffle the items without an adverse effect to the meaning of the group, then I probably shouldn't use a tuple.

每当元组感觉“自然”时,我更喜欢使用元组;坐标是一个典型的例子,其中单独的对象可以独立存在,例如,在单轴仅缩放计算中,顺序很重要。注意:如果我可以对项目进行排序或改组而不会对组的含义产生负面影响,那么我可能不应该使用元组。

I use dictionaries as a return value only when the grouped objects aren't always the same. Think optional email headers.

仅当分组对象不总是相同时,才使用字典作为返回值。想想可选的邮箱标题。

For the rest of the cases, where the grouped objects have inherent meaning inside the group or a fully-fledged object with its own methods is needed, I use a class.

对于其他情况,如果分组对象在组内部具有固有含义,或者需要具有自己方法的完全成熟对象,则使用类。

#7


22  

I prefer

def g(x):
  y0 = x + 1
  y1 = x * 3
  y2 = y0 ** y3
  return {'y0':y0, 'y1':y1 ,'y2':y2 }

it seems everything else is just extra code to do the same thing.

似乎其他一切只是额外的代码来做同样的事情。

#8


22  

>>> def func():
...    return [1,2,3]
...
>>> a,b,c = func()
>>> a
1
>>> b
2
>>> c
3

#9


16  

Python's tuples, dicts, and objects offer the programmer a smooth tradeoff between formality and convenience for small data structures ("things"). For me, the choice of how to represent a thing is dictated mainly by how I'm going to use the structure. In C++, it's a common convention to use struct for data-only items and class for objects with methods, even though you can legally put methods on a struct; my habit is similar in Python, with dict and tuple in place of struct.

Python的元组,dicts和对象为程序员提供了在小型数据结构(“事物”)的形式和便利之间的平滑权衡。对我来说,如何表示事物的选择主要取决于我将如何使用该结构。在C ++中,将结构用于仅数据项和使用方法的对象是一种常见的约定,即使您可以合法地将方法放在结构上;我的习惯在Python中类似,用dict和tuple代替struct。

For coordinate sets, I'll use a tuple rather than a point class or a dict (and note that you can use a tuple as a dictionary key, so dicts make great sparse multidimensional arrays).

对于坐标集,我将使用元组而不是点类或dict(并注意您可以使用元组作为字典键,因此dicts可以生成非常稀疏的多维数组)。

If I'm going to be iterating over a list of things, I prefer unpacking tuples on the iteration:

如果我要迭代一系列事物,我更喜欢在迭代中解包元组:

for score,id,name in scoreAllTheThings():
    if score > goodScoreThreshold:
        print "%6.3f #%6d %s"%(score,id,name)

...as the object version is more cluttered to read:

...因为对象版本更杂乱阅读:

for entry in scoreAllTheThings():
    if entry.score > goodScoreThreshold:
        print "%6.3f #%6d %s"%(entry.score,entry.id,entry.name)

...let alone the dict.

......更别说这个词了。

for entry in scoreAllTheThings():
    if entry['score'] > goodScoreThreshold:
        print "%6.3f #%6d %s"%(entry['score'],entry['id'],entry['name'])

If the thing is widely used, and you find yourself doing similar non-trivial operations on it in multiple places in the code, then it's usually worthwhile to make it a class object with appropriate methods.

如果事物被广泛使用,并且你发现自己在代码中的多个位置对它进行类似的非平凡操作,那么通常使用适当的方法使它成为一个类对象是值得的。

Finally, if I'm going to be exchanging data with non-Python system components, I'll most often keep them in a dict because that's best suited to JSON serialization.

最后,如果我要与非Python系统组件交换数据,我通常会将它们保存在dict中,因为它最适合JSON序列化。

#10


15  

Generally, the "specialized structure" actually IS a sensible current state of an object, with its own methods.

通常,“专用结构”实际上是对象的合理当前状态,具有其自己的方法。

class Some3SpaceThing(object):
  def __init__(self,x):
    self.g(x)
  def g(self,x):
    self.y0 = x + 1
    self.y1 = x * 3
    self.y2 = y0 ** y3

r = Some3SpaceThing( x )
r.y0
r.y1
r.y2

I like to find names for anonymous structures where possible. Meaningful names make things more clear.

我喜欢在可能的情况下找到匿名结构的名称。有意义的名字使事情变得更加清晰。

#11


14  

+1 on S.Lott's suggestion of a named container class.

关于S.Lott建议使用命名容器类的+1。

For python 2.6 and up, a named tuple provides a useful way of easily creating these container classes, and the results are "lightweight and require no more memory than regular tuples".

对于python 2.6及更高版本,命名元组提供了一种轻松创建这些容器类的有用方法,结果是“轻量级,并且不需要比常规元组更多的内存”。

#12


3  

In languages like Python, I would usually use a dictionary as it involves less overhead than creating a new class.

在像Python这样的语言中,我通常会使用字典,因为它比创建新类所需的开销更少。

However, if I find myself constantly returning the same set of variables, then that probably involves a new class that I'll factor out.

但是,如果我发现自己经常返回相同的变量集,那么这可能涉及一个我将要考虑的新类。

#13


3  

I would use a dict to pass and return values from a function:

我会使用dict来传递和返回函数的值:

Use variable form as defined in form.

使用表单中定义的变量形式。

form = {
    'level': 0,
    'points': 0,
    'game': {
        'name': ''
    }
}


def test(form):
    form['game']['name'] = 'My game!'
    form['level'] = 2

    return form

>>> print(test(form))
{u'game': {u'name': u'My game!'}, u'points': 0, u'level': 2}

This is the most efficient way for me and for processing unit.

这对我和处理单元来说是最有效的方式。

You have to pass just one pointer in and return just one pointer out.

你必须只传入一个指针并返回一个指针。

You do not have to change functions' (thousands of them) arguments whenever you make a change in your code.

无论何时在代码中进行更改,都不必更改函数(数千个)参数。

#14


2  

"Best" is a partially subjective decision. Use tuples for small return sets in the general case where an immutable is acceptable. A tuple is always preferable to a list when mutability is not a requirement.

“最佳”是一个部分主观的决定。在可接受不可变的一般情况下,使用元组作为小返回集。当不需要可变性时,元组总是优于列表。

For more complex return values, or for the case where formality is valuable (i.e. high value code) a named tuple is better. For the most complex case an object is usually best. However, it's really the situation that matters. If it makes sense to return an object because that is what you naturally have at the end of the function (e.g. Factory pattern) then return the object.

对于更复杂的返回值,或者对于形式有价值的情况(即高价值代码),命名元组更好。对于最复杂的情​​况,对象通常是最好的。然而,重要的是情况。如果返回一个对象是有意义的,因为这是你在函数结束时自然拥有的(例如工厂模式)然后返回对象。

As the wise man said:

正如智者所说:

Premature optimization is the root of all evil (or at least most of it) in programming.

过早优化是编程中所有邪恶(或至少大部分)的根源。