파이썬 확장 내장 클래스

다음 코드를보고 :

#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 ·은 10000 +를 볼

추천

출처blog.csdn.net/chengsilin666/article/details/83590687