gpt4 book ai didi

python - 在Python中将函数调用的结果分配在一行中

转载 作者:行者123 更新时间:2023-11-30 23:03:41 24 4
gpt4 key购买 nike

当结果在 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()Cat 类上方的注释所示。 That's what's recommended here ,例如。

假设我们有充分的理由不允许这样做。也许我们喜欢从变量名称进行赋值的清晰度(如果它们比xy更有意义),或者也许该对象主要不是一个容器。也许字段是属性,所以访问实际上涉及到方法调用。不过,我们不必假设其中任何一个来回答这个问题; Cat 类可以从表面上看。

This question已经涉及如何以最佳方式设计函数/类; 如果函数的预期返回值已经明确定义并且不涉及类似元组的访问,那么返回时接受多个值的最佳方式是什么

最佳答案

我强烈建议使用多个语句,或者只保留结果对象而不解压其属性。也就是说,您可以使用 operator.attrgetter 来实现此目的:

from operator import attrgetter
a, b, c = attrgetter('a', 'b', 'c')(foo())

关于python - 在Python中将函数调用的结果分配在一行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34005403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com