为Python类成员分配默认参数
我正在尝试从dict实例化一个类。在类构造函数中,如果未给定默认值,我会为某些类成员指定默认值:为Python类成员分配默认参数,python,arguments,Python,Arguments,我正在尝试从dict实例化一个类。在类构造函数中,如果未给定默认值,我会为某些类成员指定默认值: class Country(object): def __init__(self, continent, country = "Zimbabwe"): # do stuff 我从中实例化的dict具有与我的类成员同名的键。我从格言中举例如下: country = Country( continent = dictionary["continent"], co
class Country(object):
def __init__(self, continent, country = "Zimbabwe"):
# do stuff
我从中实例化的dict具有与我的类成员同名的键。我从格言中举例如下:
country = Country(
continent = dictionary["continent"],
country = default_value if "country" not in dictionary else dictionary["country"]
)
country = Country.default_values["country"] if "country" not in dictionary else dictionary["country"]
可以看出,字典可能没有对应于类名的键。在这种情况下,如果键country不存在,我希望将类成员国保留为其默认值,即津巴布韦。有没有一种优雅的方法可以做到这一点?以以下方式的事物:
country = dictionary["country"] if "country" in dictionary else pass
然而,这是不可能的。我知道我可以作为Country类的静态成员拥有一个默认值字典,并且可以这样做:
country = Country(
continent = dictionary["continent"],
country = default_value if "country" not in dictionary else dictionary["country"]
)
country = Country.default_values["country"] if "country" not in dictionary else dictionary["country"]
但这似乎有点过分了。有更好的方法吗?您可以使用**映射调用语法将字典应用为关键字参数:
Country('Africa', **dictionary)
如果字典有一个国家/地区键,它将作为关键字参数传递给_init__方法。如果没有,则将country设置为方法签名中指定的默认值
演示:
超出大陆和国家之外的任何其他关键字参数都会以这种方式出现在字典中。您可以使用它来支持任意参数,或者忽略传入的其他关键字参数,而不引发异常。如果字典中可能包含未在_uinit_;@MartijnPieters Corrected中使用的键,请不要忘记在参数列表中使用**kwargs。您不需要在括号内使用反斜杠