0

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..

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

THis is how it looks...>>> for c in c1.all_contacts: ... print(c) ... <__main__.Contact instance at 0x00B56AA8>
@user1050619: Yes, that is output by the default __repr__ method for your object. You want to override the default __repr__ method with a new one that prints how you want.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.