[英]super constructor use *args and **kwargs for __init__
Say we have a base class Person and a subclass Employee (see code at the bottom). 假设我们有一个基类Person和一个子类Employee(请参阅底部的代码)。
After coding a while, I found I need to add more attributes to base: 经过一段时间的编码,我发现我需要向base添加更多属性:
class Person:
def __init__(self, first, last, new_att1, new_att2):
Then I need to goto subclass, modify to following: 然后我需要转到子类,修改为以下内容:
class Employee(Person):
def __init__(self, first, last, new_att1, new_att2, staffnum):
Person.__init__(first, last, new_att1, new_att2)
self.staffnumber = staffnum
Say I have 5 subclasses. 假设我有5个子类。 Each time I update the base class attribute, I need to repeat above for all 5 subclasses.
每次更新基类属性时,都需要对所有5个子类重复以上操作。 Anyone can help to point out an elegant way to manage it?
有人可以帮助您指出一种优雅的管理方式吗?
Original class: 原始班级:
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
One option is to use keyword arguments only (which is a good idea anyway when you have many arguments): 一种选择是仅使用关键字参数(无论如何,如果您有很多参数,这是一个好主意):
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,
)
The downside is that the subclass constructors don't have an explicit signature any more, which makes them harder to read and reason about. 缺点是子类构造函数不再具有显式签名,这使它们更难以阅读和推理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.