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 ビュー10000 +

おすすめ

転載: blog.csdn.net/chengsilin666/article/details/83590687