Python面向对象——重写与Super

1本文的意义

如果给已经存在的类添加新的行为,采用继承方案

如果改变已经存在类的行为,采用重写方案

2图解继承、重写与Super

注:上面代码层层关联。super()可以用到任何方法里进行调用,本文只用在了__init__方法中,通过重写和调用super,可以修改所有方法。

上面类的实例化:

3代码验证

class ContactList(list):
    def search(self, name):
        matching_contacts = []
        for contact in self:
            if name in contact.name:
                matching_contacts.append(contact)
        return matching_contacts

class Contact:
    all_contacts = ContactList()
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.all_contacts.append(self)
        
        
class Friend(Contact):
    def __init__(self, name, email, phone):
        super().__init__(name, email)
        self.phone = phone
        
contact1 = Contact("Zhang San", "ZhangSan@qq.com")
contact2 = Contact("Li Si", "LiSi@qq.com")
contact3 = Contact("WangWu", "WangWu@qq.com")

myFriend1 = Friend("LiLi", "Lili@qq.con", 666666)
myFriend2 = Friend("YueYue", "Yueyue@qq.con", 888888)

In [1]: Contact.all_contacts  # 列表记录了实例化的5个对象
[<__main__.Contact at 0x22d6a877048>,
 <__main__.Contact at 0x22d6a871fd0>,
 <__main__.Contact at 0x22d6a877080>,
 <__main__.Friend at 0x22d6a8770b8>,
 <__main__.Friend at 0x22d6a877160>]

In [2]: [c.name for c in Contact.all_contacts.search('Li')]
['Li Si', 'LiLi']

参考:本文参考学习《Python3 Object Oriented Programming》,根据自己理解改编,Dusty Phillips 著

原文地址:https://www.cnblogs.com/brightyuxl/p/8810663.html