将dict传递给构造函数?
问题描述:
我想将字典传递给对象的构造函数以用作kwarg.
I'd like to pass a dict to an object's constructor for use as kwargs.
很明显:
foo = SomeClass(mydict)
只传递一个参数,而不是字典的内容. las:
Simply passes a single argument, rather than the dict's contents. Alas:
foo = SomeClass(kwargs=mydict)
似乎更明智的选择也不起作用.我想念什么?
Which seems more sensible doesn't work either. What am I missing?
答
使用情况:
foo = SomeClass(**mydict)
这将解压缩dict值并将其传递给函数.
this will unpack the dict value and pass them to the function.
例如:
mydict = {'a': 1, 'b': 2}
SomeClass(**mydict) # Equivalent to : SomeClass(a=1, b=2)