3

I am new to OOP in Python and working on inheritance concept. I came across the following code:

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'm wondering why do we use self.all_contacts.append(self) and how does for contact in self work ?. If I understood correctly, self appoints to the instance of a class (object), and appending to a list is not trivial to me.

3 Answers 3

4

all_contacts is a class variable -- it is unique to the class, not to each instance. It can be accessed with Contact.all_contacts. Whenever you create a new contact, it is appended to this list of all contacts.

ContactList inherits from list, so for contact in self works the same way as for i in [1,2,3] -- it will loop through all the items that it contains. The only thing that it does differently from a list is implement a new method, search.

3

Well, basically you create a list of Contact and appending self add the current contact in the all_contacts list.

Now for your questions,

I'm wondering why do we use self.all_contacts.append(self)

We would use that because all_contacts is a class variable which means that the list will be shared among all Contact instances.

how does for contact in self work?

Well, as you said, since self represents the current instance, calling for contact in self is allowing you to iterate on the current Contacts list.

In other words, your code sample let you create Contact instance which is appended in a class variable (shared) automatically. Now, by providing a ContactList class that inherits from list, they allow you to use the implemented search method which will return you another list of Contact based on your search filter.

3

all_contacts is a class variable of Contact, initialized as an instance of ContactList, a subclass to list, so when a new Contact instance is instantiated via the __init__ method, self is assigned with the new instance being instantiated and self.all_contacts.append(self) would add the new Contact instance to the all_contacts list. This way, Contact.all_contacts will maintain a list of all Contact instances that have been instantiated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.