如果在python中按名称(不能索引)存储结果,如何将函数调用的结果分配给多个变量。
例如(在Python 3中测试),
import random
# foo, as defined somewhere else where we can't or don't want to change it
def foo():
t = random.randint(1,100)
# put in a dummy class instead of just "return t,t+1"
# because otherwise we could subscript or just A,B = foo()
class Cat(object):
x = t
y = t + 1
return Cat()
# METHOD 1
# clearly wrong; A should be 1 more than B; they point to fields of different objects
A,B = foo().x, foo().y
print(A,B)
# METHOD 2
# correct, but requires two lines and an implicit variable
t = foo()
A,B = t.x, t.y
del t # don't really want t lying around
print(A,B)
# METHOD 3
# correct and one line, but an obfuscated mess
A,B = [ (t.x,t.y) for t in (foo(),) ][0]
print(A,B)
print(t) # this will raise an exception, but unless you know your python cold it might not be obvious before running
# METHOD 4
# Conforms to the suggestions in the links below without modifying the initial function foo or class Cat.
# But while all subsequent calls are pretty, but we have to use an otherwise meaningless shell function
def get_foo():
t = foo()
return t.x, t.y
A,B = get_foo()
我们不想做什么
如果结果是可转位的(Cat
扩展元组/列表,我们使用了namedtuple等),我们可以简单地编写A,B = foo()
,如{上面的注释中所示{1}}课程。例如That's what's recommended here。
我们假设我们有充分的理由不允许这样做。也许我们喜欢从变量名称中分配清晰度(如果它们比Cat
和x
更有意义),或者对象主要不是容器。也许字段是属性,因此访问实际上涉及方法调用。我们不必承担任何人回答这个问题; y
课程可以按面值进行。
This question已经讨论了如何以最佳方式设计函数/类; 如果函数的预期返回值已经很好地定义并且不涉及类似元组的访问,那么在返回时接受多个值的最佳方法是什么?
答案 0 :(得分:3)
我强烈建议使用多个语句,或者只保留结果对象而不解压缩其属性。也就是说,您可以使用operator.attrgetter
:
from operator import attrgetter
a, b, c = attrgetter('a', 'b', 'c')(foo())