Online Tutorials & Training Materials | STechies.com
Register Login

Polymorphism and Inheritance in Python

|| 0

Polymorphism and Inheritance in Python
Stechies

What Is Polymorphism in Python?

Sometimes objects are available in different forms of types. Say, if button is an object in the reckoning, then it is possible to have draw outputs in different forms/ types - check button, round button, square button, button with images, etc. However, they all share a similar logic: onClick() and can be accessed via the same method. This concept is best defined as polymorphism.

The term polymorphism has its origin the Greek words poly meaning many and morphism meaning form. It creates structures that are capable of taking or using different forms of objects.

Example of Polymorphism in Python

class Hindustan():
	def capital(self):    
		print("New Delhi is the capital of Hindustan.")
	def language(self):
		print("Hindi the primary language of Hindustan.")
	def type(self):
		print("Bharat is a developing country.")   
class America():
	def capital(self):
		print("Washington, D.C. is the capital of America.")
        def language(self): 
		print("English is the primary language of America.")
	def type(self):  
		print("America is a developed country.") 
obj_hind = Hindustan() 
obj_Ameca = America() 
for country in (obj_hind, obj_Ameca):
country.capital() 
country.language()
country.type()

Output:

New Delhi is the capital of Hindustan. 
Hindi the primary language of Hindustan.
Bharat is a developing country.
Washington, D.C. is the capital of America.
English is the primary language of America.
America is a developed country.

Polymorphism with Abstract Class Methods

Polymorphism with an abstract class is one of the most used methods in Python. The abstract structure finds its definition in the Document class. In the event of the user creating an editor, it will be difficult for him to know in advance about the type of documents that will be opened in due course - word format or pdf format? The method of using polymorphism with abstract class helps in accessing them with ease rather than having numerous types for each document.
In order to get the right result, an abstract class called document has to be created.

The newly created class will not have any implementations; however, it will succeed in defining the structure that will be contained by all forms (this will be in the form of functions). Once the function show() is defined, then both word and pdf documents must contain the show() function.

Example Abstract Class Methods

# An abstract class.
class DocAbstract :     
    def __init__(self, name):         
        self.name = name         
    # A method can not be used, because it always throws an error.
    def show(self):
        raise NotImplementedError("Subclass must implement abstract method")
class PDF(DocAbstract):
    # Override method of parent class
    def show(self):
        print ("Show PDF document:", self.name)         
class Word(DocAbstract):     
    def show(self):
        print ("Show Word document:", self.name)
documents = [ PDF("Python abstract tutorial"),
              Word("Java Input Output Tutorial"),
              PDF("Python Date & Time Tutorial")]     
for doc in documents :     
doc.show()

Output:

Show PDF document: Python abstract tutorial
Show Word document: Java Input Output Tutorial
Show PDF document: Python Date & Time Tutorial

Polymorphism with a Function

The following program depicts the use of polymorphic functions in the functional programming language, Python.

Example polymorphism with function

# A simple Python function to demonstrate Polymorphism
def multiply(a, b, z=1):
	return a * b*z
# Driver code 
print(multiply(3, 4)) 
print(multiply(2, 3, 4))

Output:

12
24

What is inheritance in Python?

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 

# A Python program to demonstrate inheritance 
class man(object): 
	# Constructor 
	def __init__(self, name): 
		self.name = name 
	# To get name 
	def getName(self): 
		return self.name 
	# To check if this man is employee 
	def isEmployee(self): 
		return False
# Inherited or Sub class (Note Person in bracket) 
class Employee(man): 
	# Here we return true 
	def isEmployee(self): 
		return True
# Driver code 
emp = man("inheritance-") # An Object of Person 
print(emp.getName(), emp.isEmployee()) 
emp = Employee("inheritance-") # An Object of Employee 
print(emp.getName(), emp.isEmployee())

Output

inheritance- False
inheritance- True 

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 ExamInher1(object):
	def __init__(self):
		self.str1 = "Example of inhertence1"
		print "ExamInher1"
class ExamInher2(object): 
	def __init__(self): 
		self.str2 = "Example of inhertence2"		
		print "ExamInher2"
class Derived(ExamInher1, ExamInher2): 
	def __init__(self): 		
		# Calling constructors of inhertence and inhertence 2 classes 
		ExamInher1.__init__(self) 
		ExamInher2.__init__(self) 
		print "Derived"		
	def printStrs(self): 
		print(self.str1, self.str2)
ob = Derived() 
ob.printStrs()

Output

ExamInher1
ExamInher2
Derived
('Example of inhertence1', 'Example of inhertence2')

Multilevel Inheritance in Python

# A Python program to demonstrate multilevel inheritance
# Base or Super class. Note object in bracket.
# (Generally, object is made ancestor of all classes)
class multiInher(object):
	# Constructor
	def __init__(self, name):
		self.name = name
	# To get name
	def getName(self):
		return self.name
# Inherited or Sub class (Note Person in bracket)
class younggen(multiInher):
	# Constructor 
	def __init__(self, name, age):
		multiInher.__init__(self, name)
		self.age = age
	# To get name 
	def getAge(self):
		return self.age
# Inherited or Sub class (Note Person in bracket)
class Grandyounggen(younggen):
	# Constructor 
	def __init__(self, name, age, address):
		younggen.__init__(self, name, age)
		self.address = address

	# To get address
	def getAddress(self):
		return self.address	
# Driver code 
g = Grandyounggen("Child", 23, "Gurgaon") 
print(g.getName(), g.getAge(), g.getAddress())

Output:

('Child', 23, 'Gurgaon') 

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

Literally, polymorphism in Python refers to its ability to take on various forms. It allows for the declaration of methods / functions in the child class. The newly defined function will possess the same name as is defined by the specific parent class. As is already known, all methods belonging to the parent class is inherited by the child class. However, it is common for coders to encounter certain methods/ functions that have been inherited by the child class from the parent class but do not fit in to perfection. In order to avoid runtime errors, the specific methods have to be re-implemented in the child class. The ensuing process is referred to as Method Overriding.

Once a method or function has been overridden in the child class, then the new version of the function is to be called on the basis of the object type that is used for the purpose of invoking the same. In the event of a child class object being used for calling an overridden method, the child class version belonging to the function will be called. Conversely, in case of the parent class object being used for calling any overridden method, the version belonging to the parent class function will be called.

Conclusion

Inheritance and polymorphism in python are two 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.

Polymorphism is when various kinds respond to same function. In other words, it means that the same functions are defined on different types of objects.  It is a very useful attribute of Python programmers as it makes coding easier and more intuitive. In Python, protocols are provided for coding purposes. These protocols are useful for implementing consistent behavior for different kinds of built-in objects in Python.


Related Articles