我试图从dict实例化一个类。在类构造函数中,如果没有给出,我将默认值分配给某些类成员:
class Country(object):
def __init__(self, continent, country = "Zimbabwe"):
# do stuff
我实例化的dict具有与我的类成员同名的键。我像这样从dict中实例化:
country = Country(
continent = dictionary["continent"],
country = default_value if "country" not in dictionary else dictionary["country"]
)
可以看出,字典可能没有与类名对应的密钥。在这种情况下,如果密钥“country”不存在,我想让该类成员国处于其默认值,即“津巴布韦”。有一种优雅的方式来做到这一点?以下的方式:
country = dictionary["country"] if "country" in dictionary else pass
然而,这是不可能的。我知道我可以将默认值的字典作为Country类的静态成员,并且这样做:
country = Country.default_values["country"] if "country" not in dictionary else dictionary["country"]
但这似乎有点矫枉过正。有更好的方法吗?
答案 0 :(得分:5)
您可以使用**mapping
调用语法将字典应用为关键字参数:
Country('Africa', **dictionary)
如果字典有country
键,它将作为关键字参数传递给__init__
方法。如果没有,则country
设置为方法签名中指定的默认值。
演示:
>>> class Country(object):
... def __init__(self, continent='Europe', country='Great Britain'):
... print 'Continent: {}, Country: {}'.format(continent, country)
...
>>> dictionary = {'continent': 'Africa', 'country': 'Zimbabwe'}
>>> Country(**dictionary)
Continent: Africa, Country: Zimbabwe
<__main__.Country object at 0x100582550>
>>> Country(**{'country': 'France'})
Continent: Europe, Country: France
<__main__.Country object at 0x100582510>
对于函数签名,有一种镜像语法;参数列表中的**mapping
捕获未明确命名的关键字参数:
def __init__(self, continent='Europe', country='Great Britain', **kw):
除continent
和country
之外的任何其他关键字参数都会以字段kw
的方式结束。您可以使用它来支持任意参数,或忽略传入的其他关键字参数而不抛出异常。