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.