Online Tutorials & Training Materials | STechies.com
Register Login

What is Inheritance in Python?

|| 0

What is Inheritance in Python?
Stechies

Python Inheritance

Inheritance is an important mechanism in Python that helps coders create a new class referred to as the child class. The child class has its origin in an existing class referred to as the parent class. Along with inheriting the properties and attributes of the parent class, new attributes are added to the child class to make it unique.

Inheritance comes in useful when classes having very similar properties have to be created for any given code.

The program has to be written keeping in mind the properties that are already present in the parent class. Thereafter, new lines have to be included to define newer attributes and properties for the child class. Overall, inheritance saves coders from duplicating numerous lines of code.

Example of Inheritance in Python

class admin:
  def __init__(self, fname, lname, dep):
    self.firstname = fname
    self.lastname = lname
    self.dep = dep
  def message(self):
    print("Employee Name "+self.firstname,self.lastname +" is from "+self.dep+" Department")

class Employee(admin):
  pass

x = Employee("Stechies", "Tutorial", "Development")
x.message() 

Output

Employee Name Stechies Tutorial is from Development Department

Class polygon has different data attributes for storing the number of sides (n) as well as the magnitude of each side in the form of a list (sides).
The magnitude of every side is taken by the method inputSides() while the method dispSides() is used for displaying them properly. A polygon with three sides is a triangle.

Here, a class named Triangle is created; it is inherited from class Polygon. By doing so, the attributes present in the parent class (Polygon) are automatically inherited by the child class (Triangle). This method of code-reusability prevents duplication of code and saves upon valuable time.

Even though the functions inputSides() or dispSides() were not defined specifically for class Triangle, it was possible to use the same because of the inheritance mechanism. In case any attribute is not easily accessed in a given class then the search is shifted to the base class. This is repeated recursively in case the base class is derived from any other class.

Types of Inheritance in Python and Examples of PythonClass Inheritance

There are two kinds of inheritance in Python - multiple and multilevel inheritance.

Multiple Inheritance in Python

# Python example to show working of multiple inheritance
class grand_parent(object):
    def __init__(self):
        self.str1 = "Grant Parent Class String"


class parent(object):
    def __init__(self):
        self.str2 = "Parent Class String"


class child(grand_parent, parent):
    def __init__(self):

        grand_parent.__init__(self)
        parent.__init__(self)

    def printStrs(self):
        print(self.str1, self.str2)

    def printsum(self):
        print("Child Class Function")
        print(15+19*2)

ob = child()
ob.printStrs()
ob.printsum()

Output

('Grant Parent Class String', 'Parent Class String')
Child Class Function
53 

Multilevel Inheritance in Python

class Human:
    def speak(self):
        print("Human Speaking")
#The child class Parent inherits the base class Human
class Parent(Human):
    def eat(self):
        print("Eat Food")
#The child class child inherits another child class Parent
class child(Parent):
    def drink(self):
        print("Drink Milk")
d = child()
d.eat()
d.speak()
d.drink() 

Output:

Eat Food
Human Speaking
Drink Milk 

Multiple Inheritance refers to the mechanism when the properties of multiple classes are inherited by a single child class. Say, there are two classes - A and B - and the programmer desires to create a new class that has the properties of both A and B, then:

The above lines depict how the characteristics of both classes A and B are inherited in the same child class C with the help of the multiple inheritance mechanism. As is visible above, instead of mentioning just one class name within parentheses for defining the child class, two different class names, separated by a comma, have been mentioned to do the needful. As the properties of any given number of classes can be inherited by the child class, the syntax can be written as:

In case of multilevel inheritance, the classes will be inherited at multiple separate levels. Say, there are three classes named A, B and C - A is the super-class, B the sub(child) class, and C is referred to as the sub class of B.

Let’s refer to a simple example to explain the mechanism of multilevel inheritance in Python:

Overriding Methods in Python

Example Overriding Methods in Python

class Rtangle():
	def __init__(self,length,breadth):
		self.length = length
		self.breadth = breadth
	def getArea(self):
		print self.length*self.breadth," The area of rectangle"
class Square(Rtangle):
	def __init__(self,side):
		self.side = side
		Rtangle.__init__(self,side,side)
	def getArea(self):
		print self.side*self.side," The area of square"
s = Square(5)
r = Rtangle(3,5)
s.getArea()
r.getArea()

Output

25  The area of square
15  The area of rectangle

Conclusion

Inheritance in python is very useful mechanisms that help programmers attain the best results for their codes. Inheritance allows coders to create any general class and then extend the same to specialized class. Inheritance also sets the base for writing better codes. Inheritance helps child classes access all data fields as well as the methods / functions of the parent class/ classes. In addition, more fields and methods can be added without having to write the already written codes from the scratch -thereby eliminating the concerns of code duplication.