为Python类成员分配默认参数

Sle*_*der -1 python arguments

我试图从一个字典中实例化一个类.在类构造函数中,如果没有给出,我将默认值分配给某些类成员:

class Country(object):
    def __init__(self, continent, country = "Zimbabwe"):
        # do stuff
Run Code Online (Sandbox Code Playgroud)

我实例化的字典具有与我的类成员同名的键.我像这样从dict中实例化:

country = Country(
    continent = dictionary["continent"],
    country   = default_value if "country" not in dictionary else    dictionary["country"]
)
Run Code Online (Sandbox Code Playgroud)

可以看出,字典可能没有与类名对应的密钥.在这种情况下,如果密钥"country"不存在,我希望将类成员国保留为其默认值,即"津巴布韦".有一种优雅的方式来做到这一点?以某种方式的东西:

country = dictionary["country"] if "country" in dictionary else pass
Run Code Online (Sandbox Code Playgroud)

然而,这是不可能的.我知道我可以将默认值的字典作为Country类的静态成员,并且这样做:

country = Country.default_values["country"] if "country" not in dictionary else dictionary["country"]
Run Code Online (Sandbox Code Playgroud)

但这似乎有点矫枉过正.有更好的方法吗?

Mar*_*ers 5

您可以使用**mapping调用语法将字典应用为关键字参数:

Country('Africa', **dictionary)
Run Code Online (Sandbox Code Playgroud)

如果字典有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>
Run Code Online (Sandbox Code Playgroud)

对于函数签名,有一种镜像语法; **mapping在参数列表中捕获未明确命名的关键字参数:

def __init__(self, continent='Europe', country='Great Britain', **kw):
Run Code Online (Sandbox Code Playgroud)

任何额外的关键字参数之外continent,并country在字典中结束了kw这种方式.您可以使用它来支持任意参数,或忽略传入的其他关键字参数而不抛出异常.