继承:不同的参数集合
在项目中,我们常常会遇到最初设计的参数字段不够,导致我要修改很多代码,对于这种额外参数的情况我们改如何去处理呢?代码如下
class Contact: # 这个类里面定义了name和email两个属性 def __init__(self, name, email): self.name = name self.email = email class AddressHolder: def __init__(self, street, city, state, code): # 这个类里面定义了 streer,city,state,code属性 self.street = street self.city = city self.state = state self.code = code # 现在有个需求:还要加一个电话的属性进去,该怎么处理呢?
# 这里使用的是继承的方法
class Fried(Contact, AddressHolder):
def __init__(self, name, email, street, city, state, code, phone): Contact.__init__(self, name, email) AddressHolder.__init__(self, street, city, state, code) self.phone = phone
# 问题来了:如果是一次还好,如果像这样的需求有很多岂不是让人很头痛,其实正确的解决方案是下面这样,通过不定长参数来吸收值
解决方案如下:
class Contact: all_contacts = ContactList() def __init__(self, name="", email="", **kwargs): # 必须要写成这种键值对的方式,因为使用的kwargs super().__init__(**kwargs) self.name = name self.email = email Contact.all_contacts.append(self) class AddressHolder: def __init__(self, street="", city="", state="", code="", **kwargs): super().__init__(**kwargs) self.street = street self.city = city self.state = state self.code = code class Fried(Contact, AddressHolder): def __init__(self, phone="", **kwargs): super().__init__(**kwargs) # 在这里我们就不用管前面的参数了,只需要继承过来就行,前面的参数都被kwargs收集起来了,维护起来更加方便 self.phone = phone

浙公网安备 33010602011771号