面向对象之继承:实现搜索功能

如何使用继承的方法来实现搜索功能?以通讯录为例子演示代码

class ContactList(list): # 首先需要拓展内置类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() # 直接使用拓展类里面search方法就可以实现查询功能

    def __init__(self, name, email):
        self.name = name
        self.email = email
        Contact.all_contacts.append(self)


# 在通讯录里面查找'John'的人员
c1 = Contact("John A","[email protected]")
c2 = Contact("John B","[email protected]")
c3 = Contact("Johan C","[email protected]")
print([i.name for i in ContactList(Contact.all_contacts).search("John")])

结果:
['John A', 'John B']

猜你喜欢

转载自www.cnblogs.com/su-sir/p/12488878.html