简体   繁体   English

** kwargs中的Python可调参数

[英]Python callable argument in **kwargs


I have following code: 我有以下代码:

def aggregate(self, **kwargs):
    for node in self:
        for prop, val in kwargs.values():
            set_val = val(node) if callable(val) else val
            setattr(node, prop, set_val)
    return self

When i'm trying to set in **kwargs a callable variable, function throw this error: 当我试图在**kwargs设置一个可调用的变量时,函数抛出这个错误:

Message: TypeError("'function' object is not iterable",)

Please help. 请帮忙。 Can't understand where the problem is 无法理解问题所在
Method call are following: obj.aggregate(my_key=_test) where _test are callable 方法调用的下列: obj.aggregate(my_key=_test)其中_test是可调用

You're iterating .values() , where each value is a single item, but you're unpacking to two names, prop and val . 你正在迭代.values() ,其中每个值都是一个单独的项目,但是你要解.values()两个名称, propval The error occurs when it effectively tries to assign prop, val = _test . 当它有效地尝试分配prop, val = _test时会发生错误。

Looks like you meant to iterate .items() , not .values() . 看起来你打算迭代.items() ,而不是.values() That way, prop would be "my_key" , and val _test as expected. 这样一来, prop"my_key" ,并val _test预期。

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

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