0

I understand that how * and ** operators generally work. In the following code [ taken from django's source ]

def curry(_curried_func, *args, **kwargs):
    def _curried(*moreargs, **morekwargs):
        return _curried_func(*(args + moreargs), **dict(kwargs, **morekwargs))
return _curried

I get how the args + moreargs part work - the [non - keyword ] arguments passed initially to the function curry and the arguments passed to the curried function returned by curry are combined. What I don't get is how the **dict(kwargs, **morekwargs) works. Could someone please explain that bit?

4

2 回答 2

2

dict(kwargs, **morekwargs)是将 2 个字典合并为 1 个的技巧(Guido不喜欢)。

>>> d = {'foo':'bar'}
>>> kwargs = {'bar':'baz'}
>>> dict(d,**kwargs)
{'foo': 'bar', 'bar': 'baz'}

因此,curried 函数获取所有传递给的 kwargs curry,并将它们添加到传递给_curried函数的附加 kwargs 中,以创建一个超级字典。该超级字典被解包并发送到_curried_func.

于 2013-06-27T14:21:40.540 回答
1

它有效地建立了两个字典的联合,kwargs并且morekwargs. 例子:

>>> kwargs = {"ham": 1, "spam": 2}
>>> morekwargs = {"spam": 3, "eggs": 2}
>>> dict(kwargs, **morekwargs)
{'eggs': 2, 'ham': 1, 'spam': 3}

这是有效的,因为dict构造函数接受关键字参数,所以它与

>>> dict(kwargs, spam=3, eggs=2)
{'eggs': 2, 'ham': 1, 'spam': 3}

最后,结果dict作为关键字参数_curried_func通过**.

于 2013-06-27T14:24:52.847 回答