Python - Write program to use __init__ method

Requirements

Write program to use __init__ method

Here is the two classes

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) 
        

Extend MySubClass and add __init__ method to it

Hint

__init__ is run when a new instance object is created: self is the new MySubSubClass object.

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 
#   w  ww.j  av a  2s . 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 

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

Result

Related Example