Python 中的动态关键字参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/337688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 19:55:18  来源:igfitidea点击:

Dynamic Keyword Arguments in Python?

python

提问by user42876

Does python have the ability to create dynamic keywords?

python有能力创建动态关键字吗?

For example:

例如:

qset.filter(min_price__usd__range=(min_price, max_price))

I want to be able to change the usdpart based on a selected currency.

我希望能够根据所选货币更改美元部分。

回答by jfs

Yes, It does. Use **kwargsin a function definition.

是的,它确实。使用**kwargs在函数定义。

Example:

例子:

def f(**kwargs):
    print kwargs.keys()


f(a=2, b="b")     # -> ['a', 'b']
f(**{'d'+'e': 1}) # -> ['de']

But why do you need that?

但你为什么需要那个?

回答by James Hopkin

If I understand what you're asking correctly,

如果我理解你的要求是正确的,

qset.filter(**{
    'min_price_' + selected_currency + '_range' :
    (min_price, max_price)})

does what you need.

做你需要的。

回答by Benjamin Pollack

You can easily do this by declaring your function like this:

你可以通过像这样声明你的函数来轻松地做到这一点:

def filter(**kwargs):

your function will now be passed a dictionary called kwargs that contains the keywords and values passed to your function. Note that, syntactically, the word kwargsis meaningless; the **is what causes the dynamic keyword behavior.

您的函数现在将传递一个名为 kwargs 的字典,其中包含传递给您的函数的关键字和值。请注意,从句法上来说,这个词kwargs是没有意义的;这**就是导致动态关键字行为的原因。

You can also do the reverse. If you are calling a function, and you have a dictionary that corresponds to the arguments, you can do

你也可以反过来做。如果你正在调用一个函数,并且你有一个对应于参数的字典,你可以这样做

someFunction(**theDictionary)

There is also the lesser used *foo variant, which causes you to receive an array of arguments. This is similar to normal C vararg arrays.

还有一个较少使用的 *foo 变体,它使您接收一组参数。这类似于普通的 C vararg 数组。

回答by Benjamin Pollack

Yes, sort of. In your filter method you can declare a wildcard variable that collects all the unknown keyword arguments. Your method might look like this:

是的,有点。在您的过滤器方法中,您可以声明一个通配符变量来收集所有未知的 关键字参数。您的方法可能如下所示:

def filter(self, **kwargs):
    for key,value in kwargs:
        if key.startswith('min_price__') and key.endswith('__range'):
            currency = key.replace('min_price__', '').replace('__range','')
            rate = self.current_conversion_rates[currency]
            self.setCurrencyRange(value[0]*rate, value[1]*rate)