[英]super constructor use *args and **kwargs for __init__
假設我們有一個基類Person和一個子類Employee(請參閱底部的代碼)。
經過一段時間的編碼,我發現我需要向base添加更多屬性:
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,
)
缺點是子類構造函數不再具有顯式簽名,這使它們更難以閱讀和推理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.