通过self._dict__更新属性

chr*_*ise 0 python class

我在这里找到了一个建议,通过自我更新批量类属性.dict .upadte所以我试过了

class test(object):
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
    def update(self, **kwargs):
        self.__dict__.update(kwargs)

d = {'a':1,'b':2,'c':3}

c = test(d)
Run Code Online (Sandbox Code Playgroud)

而且

c = test()
c.update(d)
Run Code Online (Sandbox Code Playgroud)

但是我得到了错误

TypeError: __init__() takes exactly 1 argument (2 given)
Run Code Online (Sandbox Code Playgroud)

谁能告诉我为什么这不起作用?干杯C.

Ign*_*ams 6

因为您没有正确传递值.

c = test(**d)
Run Code Online (Sandbox Code Playgroud)