0

以下のコードでは、連絡先リスト オブジェクトを出力する必要があります。

# Test.py
class ContactList(list):
    def search(self, name):
        '''Return all contacts that contain the search value
        in their name.'''
        matching_contacts = []
        for contact in self:
            if name in contact.name:
                matching_contacts.append(contact)
        return matching_contacts


class Contact:
    all_contacts = ContactList()

    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.all_contacts.append(self)

Contact の 2 つのオブジェクトを作成しましたが、all_contacts リストのすべての要素を表示したい..

4

1 に答える 1

1

どうですか:

print(Contact.all_contacts)

また:

for c in Contact.all_contacts:
    print("Look, a contact:", c)

Contactの印刷方法を制御するには、Contactクラスで__str__またはメソッドを定義する必要があります。__repr__

def __repr__(self):
    return "<Contact: %r %r>" % (self.name, self.email)

または、連絡先を代表したい場合。

于 2012-06-12T17:57:43.710 に答える