Python扩展内置类

先看下面的代码:

#ContactList类继承自python内置类list
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()#公有类,为所有类的实例对象所共享,属于List的扩展类对象
    def  __init__(self, name, email):
        self.name = name
        self.email = email
        self.all_contacts.append(self)
       
c1 = Contact('1 A','1')
c2 = Contact('2 A','1')
c3 = Contact('3 A','1')
[c.name for c in Contact.all_contacts.search('A')]

输出 结果为
在这里插入图片描述

发布了98 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/chengsilin666/article/details/83590687
今日推荐