Howdy friends, After class and objects tutorial we are moving forward with Inheritance in Python and also Python Polymorphism. Let’s start:
What is Inheritance in Python?
Inheritance is an important point of the object-oriented concept in every programming languages.
Inheritance describes is a kind of relationship between two or more classes, abstracting common details into superclass
and stored specific ones in the subclass.
- By using inheritance, We can create a class by deriving it from a preexisting class by listing the parent class in parentheses after the new class name, instead of starting from scratch.
- To create a child class, specify the parent class name inside the pair of parenthesis, followed by its name.
Example:
class Child(Parent):
pass
- In Python, every class uses inheritance and is inherited from
object
by default. - Hence, the below two definitions of
MySubClass
are same.
Definition 1
class MySubClass:
pass
Definition 2
class MySubClass(object):
pass
object
is known as a parent or superclass.MySubClass
is known as child or subclass or derived class .
Inheritance in Python Example:
class Person:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
class Employee(Person):
all_employees = []
def __init__(self, fname, lname, empid):
Person.__init__(self, fname, lname)
self.empid = empid
Employee.all_employees.append(self)
p1 = Person('George', 'smith')
e1 = Employee('Jack', 'simmons', 456342)
e2 = Employee('John', 'williams', 123656)
print(p1.fname, '-', p1.lname)
print(e1.fname, '-', e1.empid)
print(e2.fname, '-', e2.empid)
Employee
class is derived fromPerson
.
Output of Inheritance in Python:
George - smith
Jack - 456342
John - 123656
- In the above example,
Employee
class utilizes__init __
method of the parent classPerson
to create its object.
Overriding Methods:
We can always override parent class methods of Inheritance in Python. One reason for overriding parent’s methods is because we want some special or different functionality in the subclass.
Overriding Methods of Inheritance in Python Example:
class Parent:
def myMethod(self):
print ('Calling the parent method')
class Child(Parent):
def myMethod(self):
print ('Calling the child method')
a = Child()
a.myMethod()
Output:
Extending Built-in Types
Inheritance
feature can be also used to extend the built-in classes likelist
ordict
.- The following example extends
list
and createsEmployeesList
, which can identify employees, having a given search word in their first name.
Example 2
class EmployeesList(list):
def search(self, name):
matching_employees = []
for employee in Employee.all_employees:
if name in employee.fname:
matching_employees.append(employee.fname)
return matching_employees
Polymorphism in Python 3
Polymorphism
allows a subclass to override or change a specific behavior, exhibited by the parent class. Or we can say that the same function name (but different signatures) being uses for different types of code.
Polymorphism Example
In the below example, you will find
- Improvised
Employee
class with two methodsgetSalary
andgetBonus
. - Definition of
ContractEmployee
class derived fromEmployee
. It overrides functionality ofgetSalary
andgetBonus
methods found in it’s parent classEmployee
.
Example.1:
class Employee(Person):
all_employees = EmployeesList ()
def __init__(self, fname, lname, empid):
Person.__init__(self, fname, lname)
self.empid = empid
Employee.all_employees.append(self)
def getSalary(self):
return 'You get Monthly salary.'
def getBonus(self):
return 'You are eligible for Bonus.'
class ContractEmployee(Employee):
def getSalary(self):
return 'You will not get Salary from Organization.'
def getBonus(self):
return 'You are not eligible for Bonus.'
e1 = Employee('Jack', 'simmons', 456342)
e2 = ContractEmployee('John', 'williams', 123656)
print(e1.getBonus())
print(e2.getBonus())
Output
You are eligible for Bonus.
You are not eligible for Bonus.
Example.2:
class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the main spoken language of India.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the main language of USA.")
object_ind = India()
object_usa = USA()
for country in (object_ind, object_usa):
country.capital()
country.language()
country.type()
Output:
You can clearly see that in the above example how we use the same function name being uses for different types of code.
FAQs:
What will be the output of the following code?
class A:
def init(self):
print(‘one’)
def f(self): print(float()) print(hex(-255))
class B(A):
def init(self):
print(‘two’)
def f(self): print(float()) print(hex(-42))
x = B()
x.f()
two
0.0
-0x2a
What will be the output of the following code?
class class1:
a = 1
def f1(self): a = 2 class1.a += 1 print(class1.a, end=' ') print(a, end=' ')
class1().f1()
class1().f1()
2 2 3 2
Must Read the pervious articles:
In the above article, we have discussed Inheritance in Python and Polymorphism in Python3 with suitable examples. In the coming tutorial, we will discuss more on our python tutorials.