假设我们有一个基类 Person 和一个子类 Employee (请参阅底部的代码)。
编码一段时间后,我发现我需要向基础添加更多属性:
class Person:
def __init__(self, first, last, new_att1, new_att2):
然后我需要转到子类,修改为以下内容:
class Employee(Person):
def __init__(self, first, last, new_att1, new_att2, staffnum):
Person.__init__(first, last, new_att1, new_att2)
self.staffnumber = staffnum
假设我有 5 个子类。每次更新基类属性时,我都需要对所有 5 个子类重复上述操作。任何人都可以帮忙指出一种优雅的管理方式吗?
原始类:
class Person:
def __init__(self, first, last):
self.firstname = first
self.lastname = last
def __str__(self):
return self.firstname + " " + self.lastname
class Employee(Person):
def __init__(self, first, last, staffnum):
Person.__init__(first, last)
self.staffnumber = staffnum
最佳答案
一种选择是仅使用关键字参数(当您有很多参数时,这无论如何都是一个好主意):
class Person(object):
def __init__(self, firstname, lastname, new_att1, new_att2):
self.firstname = firstname
self.lastname = lastname
def __str__(self):
return "%s %s" % (self.firstname, self.lastname)
class Employee(Person):
def __init__(self, staffnumber, **kwargs):
super(Employee, self).__init__(**kwargs)
self.staffnumber = staffnumber
e = Employee(
firstname="Foo",
lastname="Bar",
staffnumber=42,
new_att1=True,
new_att2=False,
)
缺点是子类构造函数不再有显式签名,这使得它们更难以阅读和推理。
关于python - super 构造函数使用 *args 和 **kwargs 进行 __init__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40431346/