How do I properly pass a dict of key/value args to kwargs in Python?

ぃ、小莉子 提交于 2020-02-14 21:45:28

问题


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

arguments = {'spam': 'ham', 'bar': 'baz'}
print foo(**arguments)

or you could just call the function with keyword arguments:

f = Foo(foo="bar")
foo(spam='ham', bar='baz')

Your error is unrelated, you didn't define foo, you probably meant to make that a string:

settings = {'foo': 'bar'}


来源:https://stackoverflow.com/questions/14343147/how-do-i-properly-pass-a-dict-of-key-value-args-to-kwargs-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!