Python - Write program to implement __add__ method

Requirements

Write program to implement __add__ method

Add __add__ method the MySubSubClass


class MyClass:               # Define a class object 
    def setdata(self, value):   # Define class's methods 
        self.data = value       # self is the instance 
    def display(self): 
        print(self.data)        # self.data: per instance 

class MySubClass(MyClass):     # Inherits setdata 
    def display(self):                           # Changes display 
        print('Current value = "%s"' % self.data) 
        
class MySubSubClass(MySubClass):  # Inherit from MySubClass 
    def __init__(self, value):  # On "MySubSubClass(value)" 
        self.data = value 
    def __str__(self):          # On "print(self)", "str()" 
        return '[MySubSubClass: %s]' % self.data 

a = MySubSubClass('abc')           # __init__ called 
a.display()                     # Inherited method called 
print(a)                        # __str__: returns display string 

b = a + 'xyz'                   # __add__: makes a new instance 
b.display()                     # b has all MySubSubClass methods 
print(b)                        # __str__: returns display string 

Hint

__add__ is run when a MySubSubClass instance appears in a + expression.

Demo

class MyClass:               # Define a class object 
    def setdata(self, value):   # Define class's methods 
        self.data = value       # self is the instance 
    def display(self): 
        print(self.data)        # self.data: per instance 
#   ww w .  j  a  va 2  s.  c  o  m
class MySubClass(MyClass):      # Inherits setdata 
    def display(self):          # Changes display 
        print('Current value = "%s"' % self.data) 
        
class MySubSubClass(MySubClass):# Inherit from MySubClass 
    def __init__(self, value):  # On "MySubSubClass(value)" 
        self.data = value 
    def __add__(self, other):   # On "self + other" 
        return MySubSubClass(self.data + other) 
    def __str__(self):          # On "print(self)", "str()" 
        return '[MySubSubClass: %s]' % self.data 
    def mul(self, other):       # In-place change: named 
        self.data *= other 

a = MySubSubClass('abc')        # __init__ called 
a.display()                     # Inherited method called 
print(a)                        # __str__: returns display string 

b = a + 'xyz'                   # __add__: makes a new instance 
b.display()                     # b has all MySubSubClass methods 
print(b)                        # __str__: returns display string

Result

Related Example