简体   繁体   English

Python3.4 ** kwargs,意外的关键字参数

[英]Python3.4 **kwargs, unexpected keyword argument

I have a dictionary of functions, all of which use 1 or 2 optional arguments. 我有一个函数字典,所有函数都使用1或2个可选参数。 I want to iterate through this dictionary and pass both arguments to each iterated function, and have the functions that only need 1 argument to ignore the second. 我想遍历此字典并将两个参数都传递给每个迭代函数,并使这些函数只需要一个参数即可忽略第二个。 In these cases, however, I get an unexpected keyword argument error. 但是,在这些情况下,我收到了意外的关键字参数错误。

def getNumFrames(self, **kwargs):
    return len(self.x)

def getConcentration(self, **kwargs):
    if ((not gradient) or (not maxX)):
        return 0
    return (gradient / maxX) * self.x[0]

fields = {'numFrames': getNumFrames, 'concentration': getConcentration}


for field, fieldFunction in fields.items():
        for track in tracks:
             fieldFunction(object, maxX = 10, gradient = 2)

In this example, getConcentration would work, but getFrames would say maxX is an unexpected keyword. 在此示例中,getConcentration可以工作,但是getFrames会说maxX是意外的关键字。

*I edited my post to include my actual minimalist code, as was suggested. *根据建议,我对帖子进行了编辑,以包含实际的极简代码。

A much better way to avoid all of this trouble is to use the following paradigm: 避免所有这些麻烦的更好的方法是使用以下范例:

def func(obj, **kwargs):
    return obj + kwargs.get(a, 0) + kwargs.get(b,0)

This makes use of the fact that kwargs is a dictionary consisting of the passed arguments and their values and get() performs lookup and returns a default value if the key does not exist. 这利用了以下事实: kwargs是由传递的参数及其值组成的字典,如果键不存在,则get()执行查找并返回默认值。

Always access your named arguments through the dictionary kwargs . 始终通过字典kwargs访问命名参数。 This makes your life much simpler. 这使您的生活变得更加简单。

I would go about this by creating a function like the one below with the second parameter optional. 为此,我将创建一个类似于以下功能的函数,其中第二个参数为可选参数。

func (obj, a = 0, b = 0):
    return obj + a + b

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM