在函数调用中形式函数参数后跟 **kwargs

formal function arguments followed by **kwargs in Function Calls

我了解函数参数必须具有以下排序层次结构

  1. 正式的位置参数
  2. *args
  3. 关键字参数
  4. **kwargs

我收到此错误:

SyntaxError: keyword can't be an expression

在下面:

def dfDiff(old, new, **kwargs):
    # default dict of optional function arguments
    d = {'city': 'Austin',
         'capital': True,
         'indx' : 5}
    # if optional args are provided 
    if kwargs is not None:
        # find the common keys
        k_passed = kwargs.keys() & d.keys()
        # change the default value
        for k in k_passed:
            d[k] = kwargs[k]    


test_ = dfDiff(1, 2, 'city' = 'Albany')

我是否通过了错误的 **kwargs 还是存在其他问题?

正如@MichaelBianconi 在评论中所说,在提供关键字参数时,您无需将它们作为字符串括起来。只需将它们视为变量即可。 所以正确的代码是:

test_ = dfDiff(1, 2, city = 'Albany')

根据指南,关键字、等于和值之间不要有 space。

test_ = dfDiff(1, 2, city='Albany')

city='Albany',不要用引号引起来 city