Python打印一个对象

时间:2012-06-12 17:54:29

标签: python-3.x

在下面的代码中,我需要打印联系人列表对象。我该怎么办?

# 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)

我创建了2个Contact对象,但想要查看all_contacts列表中的所有元素..

1 个答案:

答案 0 :(得分:1)

怎么样:

print(Contact.all_contacts)

或:

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

要控制联系人的打印方式,您需要在Contact类中定义__str____repr__方法:

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

或者,您想要代表联系人。