Object Oriented
Programming
Inheritance
• Inheritance is the capability of one class to derive or inherit the
properties from another class.
Python Inheritance Syntax
– Example:
class Point:
x = 0
y = 0
class Point3D(Point): # Point3D extends Point
z = 0
...
2
Calling Superclass Methods
• methods: class.method(object,
parameters)
• constructors: class.__init__(parameters)
class Point3D(Point):
z = 0
def __init__(self, x, y, z):
Point.__init__(self, x, y)
self.z = z
def translate(self, dx, dy, dz):
Point.translate(self, dx, dy)
self.z += dz
3
Inheritance Example
class Person: # Parent class
# Constructor
def __init__(self, name):
self.name = name
# To get name # An Object of Person
def getName(self): emp = Person(“John”)
return self.name print(emp.getName())
print(emp.isEmployee())
# To check if this person is an employee
def isEmployee(self): # An Object of Employee
return False emp = Employee(“Ram”)
print(emp.getName())
# Inherited or Subclass print(emp.isEmployee())
class Employee(Person):
# Here we return true
def isEmployee(self):
return True
4
Subclassing (Calling
constructor of parent class)
• A child class needs to identify which class is its parent class. This can be done by
mentioning the parent class name in the definition of the child class.
Eg: class subclass_name(superclass_name):
# Python code to demonstrate how parent constructors are called.
# parent class
class Person:
def __init__(self, name, idnumber):
self.name = name
self.idnumber = idnumber # child class
def display(self): class Employee(Person):
print(self.name) def __init__(self, name, idnumber, salary, post):
print(self.idnumber) self.salary = salary
self.post = post
# invoking the constructor of parent class
Person.__init__(self, name, idnumber)
# creation of an object variable or an instance
a = Employee('Rahul', 886012, 200000, "Intern")
# calling a function of the class Person using its instance
a.display()
5
Subclassing (Calling
constructor of parent class)
Python program to demonstrate error if we forget to invoke __init__() of the
parent
• If you forget to invoke the __init__() of the parent class then its instance variables
would not be available to the child class.
class A:
def __init__(self, n='Rahul'):
self.name = n
class B(A):
def __init__(self, roll):
self.roll = roll
object = B(23)
print(object.roll) # No Error
print(object.name) # Error
6
Types of Inheritance in Python
Single Inheritance: Single inheritance enables a derived class to inherit
properties from a single parent class, thus enabling code reusability and the
addition of new features to existing code.
# Python program to demonstrate single inheritance
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")
# Driver's code
object = Child() Output:
object.func1()
object.func2()
7
Types of Inheritance in Python
Multiple Inheritance: When a class can be derived from more than one base
class this type of inheritance is called multiple inheritances. (Unlike java,
python shows multiple inheritance.)
# Python program to demonstrate multiple inheritance
# Base class1
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
# Base class2
# Driver's code
class Father:
s1 = Son()
fathername = ""
s1.fathername = "RAM"
def father(self):
s1.mothername = "SITA"
print(self.fathername)
s1.parents()
# Derived class
class Son(Mother, Father):
def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
8
Types of Inheritance in Python
Multiple Inheritance: When the method is overridden in both classes
Method Resolution Order (MRO) will take place from left to right.
class Class1: class Class1:
def m(self): def m(self):
print("In Class1") print("In Class1")
class Class2: class Class2:
def m(self): def m(self):
print("In Class2") print("In Class2")
class Class3(Class1, Class2): class Class3(Class2, Class1):
pass pass
obj = Class3() obj = Class3()
obj.m() obj.m()
Output: In Class1 Output: In Class2
NOTE: In the case of multiple inheritance, a given attribute is
first searched in the current class if it’s not found then it’s
searched in the parent classes. The parent classes are searched in
a left-right fashion and each class is searched once. 9
Types of Inheritance in Python
Multilevel Inheritance: In multilevel inheritance, features of the base class and
the derived class are further inherited into the new derived class. This is like a
relationship representing a child and a grandfather.
10
Types of Inheritance in Python
# Python program to demonstrate multilevel inheritance
# Base class
class Grandfather:
def __init__(self, grandfathername):
self.grandfathername = grandfathername
# Intermediate class
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self.fathername = fathername
# invoking constructor of Grandfather class # Driver code
Grandfather.__init__(self, grandfathername) s1 = Son('Prince', 'Rampal',
# Derived class 'Lal mani')
class Son(Father): print(s1.grandfathername)
def __init__(self, sonname, fathername, s1.print_name()
grandfathername):
self.sonname = sonname
# invoking constructor of Father class
Father.__init__(self, fathername, grandfathername)
def print_name(self):
print('Grandfather name :', self.grandfathername)
print("Father name :", self.fathername)
print("Son name :", self.sonname)
11
Types of Inheritance in Python
Hierarchical Inheritance: When more than one derived class are created from
a single base class, this type of inheritance is called hierarchical inheritance.
# Python program to demonstrate Hierarchical inheritance
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class1
class Child1(Parent): # Driver's code
def func2(self): object1 = Child1()
print("This function is in child 1.") object2 = Child2()
# Derived class2 object1.func1()
class Child2(Parent): object1.func2()
def func3(self): object2.func1()
print("This function is in child 2.") object2.func3()
12
Types of Inheritance in Python
Hybrid Inheritance: Inheritance consisting of multiple types of inheritance is
called hybrid inheritance.
Hybrid
Inheritance
Multiple
Inheritance
13
Types of Inheritance in Python
# Python program to demonstrate Hybrid inheritance
14
Function Overloading
Like other languages do, python does not support method overloading by
default. But there are different ways to achieve method overloading in Python.
The problem with method overloading in Python is that we may overload the
methods but can only use the latest defined method.
Example1: Method1 (2 Args) Method2 (3 Args)
def product(a, b): def product(a, b,c):
p = a * b p = a * b * c
print(p) print(p)
>> Product(4,5) # Error >> Product(2,3,4) # No error
Example 2:
15
How to Achieve Function
Overloading in Python
Method1 :
If we want to implement the concept of function overloading, we need to set
the default values of the parameters of the function as None. By setting the
value of functional parameters as None, we get the option of calling the
function either with or without the parameter.
Method2:
By Using Multiple Dispatch Decorator
Multiple Dispatch Decorator Can be installed by:
pip3 install multipledispatch
16
How to Achieve Function
Overloading in Python
Using Method 1: Calculate the area of figures(triangle, rectangle, square).
obj=areaClass() obj.area(19,8,77)#Area of the triangle 76.0
obj.area(18,18,18,18)#Area of the square 324
obj.area(72,38,72,38)#Area of the rectangle 2736 17
How to Achieve Function
Overloading in Python
Using Method 2: Using Multiple Dispatch Decorator
from multipledispatch import dispatch
#passing two parameter
@dispatch(int,int)
def product(first,second):
result = first*second
print(result);
#passing three parameters
@dispatch(int,int,int)
def product(first,second,third):
result = first * second * third
print(result);
#you can also pass data type of any value as per requirement
@dispatch(float,float,float)
def product(first,second,third):
result = first * second * third
print(result);
#calling product method with 2 arguments
product(2,3,2) #this will give output of 12
product(2.2,3.4,2.3) # this will give output of 17.985999999999997
18