2013-10-12 84 views
-1

我正在尝试从字典中实例化一个类。在类的构造函数,我默认值分配给一些类成员如果不给:为Python类成员分配默认参数

class Country(object): 
    def __init__(self, continent, country = "Zimbabwe"): 
     # do stuff 

我从实例化的字典具有相同的名称,我的类成员键。我从字典实例,像这样:

country = Country(
    continent = dictionary["continent"], 
    country = default_value if "country" not in dictionary else dictionary["country"] 
) 

可以看出,它是可能的字典中可能没有对应的类名的关键。在这种情况下,如果“国家”这个关键字不存在,我想离开集体成员国的默认值,即“津巴布韦”。有没有一个优雅的方式来做到这一点?方式如下:

country = dictionary["country"] if "country" in dictionary else pass 

然而这是不可能的。我知道有我可以默认值的字典作为国家类的静态成员,做到这一点,像这样:

country = Country.default_values["country"] if "country" not in dictionary else dictionary["country"] 

但似乎矫枉过正。有更好的方法吗?

+0

@MartijnPieters更正。 – iab

+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的方式。您可以使用它来支持任意参数,或者忽略传入的其他关键字参数而不引发异常。

+1

如果'dictionary'可能包含'__init__'中未使用的键,请不要忘记在参数列表中使用'** kwargs' –