Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
OOP-self question
#1
Here is a part of a code i found online while i am trying to get familiar with oop:
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
can you explain me the for loop please(
Quote: for contact in self:
),how does it go?
Reply
#2
Being a ContactList instance, self is a list instance because the ContactList class subclasses the list class. So for contact in self has the same meaning as for contact is someotherlist.
Reply
#3
So the type of self depends on what type is in between the brackets of the class, and in this case is a list of the names?
Reply
#4
Quote:So the type of self depends on what type is in between the brackets of the class
The class definition contains a potentially empty list of parent classes. The type of self is the class itself, but self can also be considered an instance of any of its parent classes or the ancestor classes of these parent classes. You can get all these types by using the inspect.getmro() method
>>> import inspect
>>> class ContactList(list):
...     pass
... 
>>> inspect.getmro(ContactList)
(<class '__main__.ContactList'>, <class 'list'>, <class 'object'>)
This shows that a ConcactList instance is also a list instance and an object instance.
Reply
#5
I would suggest you check some basic introduction on classes and inheritance
Class Basics
Class - Inheritance
and one external link - Understanding Class Inheritance in Python 3
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
The indentation of the return statement is wrong.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020