Inheritance in Python
- Inheritance is the capability of one class to derive or inherit the properties from another class.
- The newly formed classes are called derived classes, the classes that we derive from are called base classes.
- Main benefits of inheritance are code reuse and reduction of complexity of a program.
class Employee:
'Employee Base Class : Basic information of Employee'
empCount = 0
def __init__(self, id='none', name='none'):
self.name = name
self.id = id
Employee.empCount += 1
class Salary(Employee):
'Derived Class (Salary) : Inherite Employee Class'
def __init__(self,salary, id='none', name='none'):
super().__init__(id, name)
self.salary = salary
Creating Instance of Derived Class
emp1 = Salary('ABC',"Deepak",'1cr')
emp2 = Salary('1cr')
print("emp1.id : {id}, emp1.name: {name}, emp1.salary: {salary}".format(id=emp1.id, name= emp1.name, salary= emp1.salary ))
print("emp2.id : {id}, emp2.name: {name}, emp2.salary: {salary}".format(id=emp2.id, name= emp2.name, salary= emp2.salary ))
print("Total Employee : {}".format(Employee.empCount))
Output :
emp1.id : Deepak, emp1.name: 1cr, emp1.salary: ABC
emp2.id : none, emp2.name: none, emp2.salary: 1cr
Total Employee : 2
super() Function in Inheritance :
- super() is used to refer the object of parent class.
- We can call super() method to access the properties or methods of the parent class.
Different types of Inheritance in Python
- Single inheritance: When a derived class inherits from only one parent class, it is called single inheritance.
- Multiple inheritance: When a derived class inherits from multiple parent classes, it is called multiple inheritance.
'Parent (Base) Class : A
class A():
def __init__(self):
print("starting __init__() of class A ")
self.name = "Nithin T."
print("Ending of __init__() of class A ")
def display(self):
print("method of class A")
'Parent (Base) Class : B
class B():
def __init__(self):
print("starting __init__() of class B ")
self.name = "Sameer S."
print("Ending of __init__() of class B ")
def display(self):
print("method of class B")
Child (Derived) Class : C inherit A and B
class C(A, B):
pass
obj1= C() # obj1 is an instance of class C() , Constructor will be called here
print(obj1.name)
obj1.display()
Output : '
starting __init__() of class A
Ending of __init__() of class A
Nithin T.
method of class A
- In the Above example we once we instantiated class C the constructor of only parent Class A is called and not the constructor of parent Class B.
- attributes (name) and methods (display) of parent Class A is associated with the object of child class B.
class C(A, B):
def __init__(self):
print("starting __init__() of class C ")
A.__init__(self)
B.__init__(self)
print("Ending of __init__() of class C ")
obj1= C()
print(obj1.name)
obj1.display()
Output : '
starting __init__() of class C
starting __init__() of class A
Ending of __init__() of class A
starting __init__() of class B
Ending of __init__() of class B
Ending of __init__() of class C
Sameer S.
method of class A
- In the Above example we once we instantiated class C the constructor of both parent Class A and B is called one after the another.
- (obj1.name) : First Constructor of Class C is called and then constructor of Class A is called hence value of name attribute assigned to Nithin T. and after that Constructor of Class B is called hence value of name attribute override to Sameer S.
- obj1.display() : python compiler first look the method in the current class (C) if the method is not available there then it will search in Class A and B respectively. and hence In this case display() of Class A will be called.
class C(A, B):
'Class C inherit Class A and B '
def __init__(self):
print("starting __init__() of class C ")
super().__init__()
print("Ending of __init__() of class C ")
def display(self):
print("method of class C")
obj1= C()
print(obj1.name)
obj1.display()
Output : '
starting __init__() of class C
starting __init__() of class A
Ending of __init__() of class A
Ending of __init__() of class C
Nithin T.
method of class C
- In the Above example we once we instantiated class C the constructor of Class C is called and then super() method is called which invoke constructor of Class A only.
- (obj1.name) : First Constructor of Class C is called and search for the attribute name in Class "C". Since it is not there in Class "C" it will search the name attribute in Class "A" and found it there hence value of name attribute assigned to Nithin T.
- obj1.display() : python compiler first look the method in the current class (C) if the method is not available there then it will search in Class A and B respectively. and hence In this case display() of Class C will be called.
- There is no limit on the number of levels that we can inherit.
- We can achieve multilevel inheritance by inheriting one class from another which then is inherited from another class.
class A:
a = 'A'
print("Class Object attribute of {}".format(a))
def __init__(self):
print("__init__() of class A")
def display(self):
print("display() from class A")
class B(A):
b = 'B'
print("Class Object attribute of {}".format(b))
def __init__(self):
print("__init__() of class B")
def display(self):
print("display() from class B")
class C(B):
c = 'C'
print("Class Object attribute of {}".format(c))
def __init__(self):
super().__init__()
print("__init__() of class C")
def display(self):
super().display()
print("display() from class C")
c = C()
print(c.display())
print(c.a)
# Output :
Class Object attribute of A
Class Object attribute of B
Class Object attribute of C
__init__() of class B
__init__() of class C
display() from class B
display() from class C
A
class A:
def __init__(self):
print("__init__() of class A")
def display(self):
print("display() from class A")
class B(A):
def __init__(self):
print("__init__() of class B")
def display(self):
print("display() from class B")
class C(A):
def __init__(self):
super().__init__()
print("__init__() of class C")
def display(self):
super().display()
print("display() from class C")
c = C()
print(c.display())
# Output :
__init__() of class A
__init__() of class C
display() from class A
display() from class C
class A:
def __init__(self):
print("__init__() of class A")
def displayA(self):
print("display() from class A")
class B(A):
def __init__(self):
print("__init__() of class B")
def displayB(self):
print("display() from class B")
class C(A):
def __init__(self):
print("__init__() of class C")
def displayC(self):
print("display() from class C")
class D(B,C):
def __init__(self):
print("__init__() of class D")
def displayD(self):
print("display() from class D")
d = D()
print(d.displayA())
# Output :
__init__() of class D
display() from class A
Polymorphism in Python :
Polymorphism is one of the core concepts of object-oriented programming (OOP) and it describes the concept that we can access objects of different types through the same interface.
- Python Built-in Implementation of Polymorphism:
- using '+' operator:
- We can use the '+' symbol to add integers or concatenation of strings or to append the lists.
- This '+' operator acts differently depending on the type of objects it is operating upon.
a = 10 b = 20 list1 = ['a', 'b', 'c'] list2 = [1, 2, 3] print(a+b) print('Sameer' + '31') print(list1+list2)
# Output : 30 Sameer31 ['a', 'b', 'c', 1, 2, 3]
- using len() :
- We can use the len() to get the number of element of a list.
- For a string, we get the number of characters within it using len().
- For a dictionary, we get the number of keys using len().
name='SameerSingh'
list1 = ['a', 'b', 'c']
dict1 = {'a':1, 'b':2, 'c':3, 'd':4}
print(len(name)) # 11
print(len(list1)) # 3
print(len(dict1)) #4
- In below example area() methods is an example of polymorphism.
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Square:
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
rectangle = Rectangle(10, 20)
square = Square(10)
print("Area of rectangle is: ", rectangle.area())
print("Area of square is: ", square.area())
# Output :
Area of rectangle is: 200
Area of square is: 100
Polymorphism and Inheritance using Method Overriding:
Method Overriding
Method Overriding
Method Overriding is an important concept in object-oriented programming (OOP) and itallows us to redefine a method by overriding it.
- Below Two condition needs to be satisfy for Overriding a Method in Python.
- Inheritance : There should be a parent-child relationship between the classes.
- The name of the method and the parameters should be the same in the base and derived class in order to override it.
class A:
def __init__(self):
print("__init__() of class A")
def display(self):
print("display() from class A")
class B(A):
def __init__(self):
print("__init__() of class B")
def display(self):
print("display() from class B")
b = B()
print(b.display())
# Output :
__init__() of class B
display() from class B
Note : Method Overloading is not supported in Python:
class A:
def __init__(self):
print("__init__() of class A")
def display(self):
print("display() from class A")
def display(self, a):
print("display({a}) from class A".format(a))
a = A()
print(a.display())
print(a.display("Sam"))
# Output :
__init__() of class A
Traceback (most recent call last):
File "", line 12, in
TypeError: display() missing 1 required positional argument: 'a'