Home > Mobile >  Return an instance of a Class in Python
Return an instance of a Class in Python

Time:10-28

I am trying to learn about Object-oriented Programming in Python but I am a bit confuse with how to return an instance of a class.

Some background for the code I have: The Contact class is meant to have a (full) name which is required, zero or more phone numbers, and zero or more email addresses for the contact. The AddressBook class which takes a list of contacts (defined as above), and the "add_contact" method is suppose to add a contact to the address book even after creating one.

class Contact:
    def __init__(self, name = None, addresses = False, email_addresses = False):
        self.name = name
        self.addresses = addresses
        self.email_addresses = email_addresses
class AddressBook:
    def __init__(self, contacts = []):
        self.contacts = contacts
    def add_contact(self,new_contact):
        self.contacts.append(new_contact)
    def contact_by_name(self, person):
        return Contact(name = person)

So what I am trying to implement is that the "contact_by_name" method will take a name(string) and returns the contact with the given name -- i.e. it returns an instance of Contact.

Example:

julian = Contact(name="Julian Berman")
book = AddressBook(contacts=[julian])

What I want:

book.contact_by_name("Julian Berman") == julian

I tried my best to come out with the code for the "contact_by_name" method but it keeps giving me errors, can someone please send help! Thanks!

CodePudding user response:

So are you just looking for a simple search?

    def contact_by_name( self, person ):
        for c in self.contacts:
            if c.name == person:
                return c
        return None

Be sure to handle the case where the name is not found.

  • Related