0

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!

DJ-coding
  • 193
  • 12
  • 2
    Don't use `contacts = []` as default value. See https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument – Barmar Oct 26 '21 at 16:55
  • 3
    Not just *an* instance of `Contact`; *the* instance that is already in your list of `Contact`s. Also, does it make sense to have a contact without a name? If not, don't provide a default value for `name`. *Really* don't use `False` as the default value for `addresses`or `email_addresses`. They appear to be lists, not Boolean values, so they should always have list values. If you want those to be optional, use `None`, and set the attribute to `[]` if the argument is `None`. – chepner Oct 26 '21 at 16:57

1 Answers1

5

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.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30