先看下面的代码:
class ContactList(list):def search(self, name):matching_contacts = []for contact in self:if name in contact.name:matching_contacts.append(contact)return matching_contactsclass Contact:all_contacts = ContactList()def __init__(self, name, email):self.name = nameself.email = emailself.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')]
输出 结果为