In this exercise, you will get some practice with the __add__ method by implementing it for a class called ContactBook. This class represents a collection of names and phone numbers. ContactBook stores its information as a dictionary, where the key is a name and the value is a phone number or group of phone numbers. The keys and values in this dictionary are stored as strings. When printed, a ContactBook might look like this:

Respuesta :

Answer:

class ContactBook():

   def __init__(self):

       self.contacts ={}

   def __repr__(self):

       return str(self.contacts)

   def add_contact(self,name,number):

       self.contacts[name] = number

   def __add__(self, other):

       new_contact = ContactBook()

       other_contact = other.contacts.keys()

       for name,num in self.contacts.items():

           if name in other_contact:

               new_contact.add_contact(name,num or other_contact[name])

           else:

               new_contact.add_contact(name,num)

       for name,num in other.contacts.items():

           if name not in self.contacts:

               new_contact.add_contact(name, num)

       return new_contact-

cb1 = ContactBook()

cb2 = ContactBook()

cb1.add_contact('Jonathan','444-555-6666')

cb1.add_contact('Puneet','333-555-7777')

cb2.add_contact('Jonathan','222-555-8888')

cb2.add_contact('Lisa','111-555-9999')

print(cb1)

print(cb2)

cb3 = cb1+cb2

print(cb3)

Explanation:

The ContactBook class holds the contact details of an instance of the class. The class has three magic methods the '__repr__', '__init__', and the '__add__' which is the focus of the code. The add magic method in the class adds the contact book (dictionary) of two added object instance and returns a new class with the contact details of both operand instances which is denoted as self and other.

ACCESS MORE