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!

2
  • 2
    Don't use contacts = [] as default value. See stackoverflow.com/questions/1132941/… Commented Oct 26, 2021 at 16:55
  • 3
    Not just an instance of Contact; the instance that is already in your list of Contacts. 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 addressesor 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. Commented Oct 26, 2021 at 16:57

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.