Search code examples
pythonclassobjectself

What does append(self) mean in Python classes?


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.


Solution

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