gpt4 book ai didi

python - 函数的返回值作为类属性

转载 作者:行者123 更新时间:2023-12-01 03:22:44 25 4
gpt4 key购买 nike

假设我有一个像这样的函数和类,

>>> def something():
... x = 5
... y = 6
... return x, y

>>> class SomethingElse():
... def __init__(self, x, y):
... self.x = x
... self.y = y
... print(x+y)
...

我想将函数返回的内容作为属性传递给我的类,这可以吗?因为当我调用我的函数时,我只将它作为 1 个属性。

>>> S = SomethingElse(5, 6)
11
>>> S1 = SomethingElse(something)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() missing 1 required positional argument: 'y'

我真正想要的是,

>>> S1 = SomethingElse(something)
11

最佳答案

您可以使用 splat(或“解包”)运算符 *,如下所示

>>> SomethingElse(*something())
11

这可以在 Unpacking Argument Lists 中看到在 Python 教程中,通常称为参数解包。

关于python - 函数的返回值作为类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41773451/

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