首页 > 其他 > 详细

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

时间:2020-03-13 21:12:26      阅读:80      评论:0      收藏:0      [点我收藏+]

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

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","JohnA@qq.com")
c2 = Contact("John B","JohnB@qq.com")
c3 = Contact("Johan C","JohnnaC@qq.com")
print([i.name for i in ContactList(Contact.all_contacts).search("John")])

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

 

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

原文:https://www.cnblogs.com/su-sir/p/12488878.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!