在 Python 中将命名函数参数输入为命名列表[重复]

问题描述 投票:0回答:1

我正在寻找一种方法,将命名函数参数作为一个命名列表输入,而不是在使用函数时单独指定它们。

假设我有这个:

import numpy as np

class Something:

    __init__(self, one = None, two = None, three = None, **kwargs):
        self.one = one
        self.two = two
        self.three = three

    def sum(self):
        np.sum(self.one, self.two, self.three)

现在,我必须做这样的事情:

Instance = Something(one = 1, two = 2, three = 3)
Instance.sum()

但是我想做的是这样的:

Inputs = {'one' : 1, 'two': 2, 'three': 3, 'four': 4}
Instance = Something(Inputs)
Instance.sum()

你有什么解决办法吗?

python
1个回答
1
投票

使用

**
字典 扩展到函数参数中。

>>> def foo(bar, baz): return bar + baz
...
>>> foo(baz=1, bar=2)
3
>>> foo(**{'baz':1, 'bar':2})
3
© www.soinside.com 2019 - 2024. All rights reserved.