user1050619
user1050619

Reputation: 20856

Python printing a object

In the below code I need to print the contactlist object..How do I do that?

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

I have created 2 object of Contact but want to see all the elements in the all_contacts list..

Upvotes: 0

Views: 11150

Answers (1)

Ned Batchelder
Ned Batchelder

Reputation: 375484

How about:

print(Contact.all_contacts)

or:

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

To control how the Contact prints, you need to define a __str__ or __repr__ method on the Contact class:

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

or, however you want to represent the Contact.

Upvotes: 1

Related Questions