Passing dict to constructor?
I'd like to pass a dict to an object's constructor for use as kwargs.
Obviously:
foo = SomeClass(mydict)
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?
Use :
foo = SomeClass(**mydict)
this will unpack the dict value and pass them to the function.
For example:
mydict = {'a': 1, 'b': 2}
SomeClass(**mydict) # Equivalent to : SomeClass(a=1, b=2)
To pass a dictionary to a constructor you have to do so by reference, which is by preceding it with **
, like so:
foo = SomeClass(**mydict)
Try this:
SomeClass(**mydict)
精彩评论