Inheritance is the mechanism that allows programmers to create new classes from existing class. By using inhertitance programmers can re-use code they've already written.
Any new class that you create from an existing class is called sub class; existing class is called super class. The sub class gets all of the methods and state variables of the super class by default. The sub class can add new methods and state variables. The sub class can also redefine methods and state variables of its parent.
The following rules you need to know about superclasses and subclasses:
Any class can be a super class, so the syntax is the same as creating any other class:
class superclass:
.....
To create a sub class send the super class as a parameter when creating the sub class:
class subclass(superclass):
.....
Create __init__() function inside subclass and add a call to the parent's __init__() function. We can refer to the methods of super class with super().
class subclass(superclass):
def __init__(self,param1,param2):
super().__init__(param1)
self.param2 = param2
....
Alternatively, instead of using super() you can call __init__() using super class name.
class subclass(superclass):
def __init__(self,param1,param2):
superclass.__init__(self,param1)
self.param2 = param2
....
The following program demonstrates the concepts of inheritance :
Program (box.py)
#super class
class Rectangle:
def __init__(self, length, width):
self.__length = length
self.__width = width
def set_rectangle(self,length, width):
self.__length = length
self.__width = width
def get_area(self):
return self.__length * self.__width;
#sub class
class Box(Rectangle):
def __init__(self, length, width, height):
Rectangle.__init__(self,length,width)
self.__height = height
def set_box(self,length, width, height):
self.set_rectangle(length,width)
self.__height = height
def get_volume(self):
return self.get_area() * self.__height
#creating object
b = Box(12,9,10)
print("Volume is ", b.get_volume())
b.set_box(12.5, 10.5, 9.5)
print("Volume is ", b.get_volume())
Output
Volume is 1080 Volume is 1246.875