How do I properly pass a dict of key/value args to kwargs in Python?
问题 I have the following: class Foo: def __init__(self, **kwargs): print kwargs settings = {foo:"bar"} f = Foo(settings) This generates an error: Traceback (most recent call last): File "example.py", line 12, in <module> settings = {foo:"bar"} NameError: name 'foo' is not defined How do I properly pass a dict of key/value args to kwargs? 回答1: Use the **kw call convention: f = Foo(**settings) This works on any callable that takes keyword arguments: def foo(spam='eggs', bar=None): return spam, bar