首页 > 解决方案 > 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.

标签: pythonclassobjectself

解决方案


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.


推荐阅读