INHERITANCE
In Object-oriented programming, inheritance is an
important aspect. The main purpose of
inheritance is the reusability of code because we
can use the existing class to create a new class
INTRODU instead of creating it from scratch.
CTION “ The process of inheriting the properties of
the parent class into a child class is called
inheritance. “
The existing class is called a base class or parent
class and the new class is called a subclass or
child class or derived class.
SYNTAX:
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
For example, In the real world, Car is a sub-class of a Vehicle
class. We can create a Car by inheriting the properties of a Vehicle
such as Wheels, Colors, Fuel tank, engine, and add extra properties
in Car as required.
TYPES OF INHERITANCE
In Python, based upon the number of child and parent classes involved,
there are five types of inheritance. The type of inheritance are listed
below:
[Link] inheritance
[Link] Inheritance
[Link] inheritance
[Link] Inheritance
SINGLE INHERITANCE
In single inheritance, a child class inherits from a single-parent class. Here is
one child class and one parent class.
Single
Inheritance
SINGLE INHERITANCE :
EXAMPLE
# Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class’)
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class’)
# Create object of Car Output
car = Car() Inside Vehicle
# access Vehicle's info using car object class Inside Car
car.Vehicle_info()
car.car_info() class
MULTIPLE INHERITANCE
In multiple inheritance, one child class can inherit from multiple parent
classes. So here is one child class and multiple parent classes.
Multiple
Inheritance
MULTIPLE INHERITANCE :
EXAMPLE
# Parent class 1
class Person:
def person_info(self, name, age):
print('Inside Person class’)
print('Name:', name, 'Age:', age)
# Parent class 2
class Company:
def company_info(self, company_name, location):
print('Inside Company
class’)
print('Name:', company_name, 'location:',
location)
# Child class
class Employee(Person, Company):
def Employee_info(self, salary, skill):
print('Inside Employee class’)
print('Salary:', salary, 'Skill:', skill)
MULTIPLE INHERITANCE :
EXAMPLE
# Create object of Employee
emp = Employee()
# access data
emp.person_info('Jessa', 28)
emp.company_info('Google', 'Atlanta’)
emp.Employee_info(12000, 'Machine
Learning')
Output:
Inside Person class
Name: Jessa Age: 28
Inside Company class
Name: Google location: Atlanta
Inside Employee class
Salary: 12000 Skill: Machine Learning
MULTILEVEL INHERITANCE
In multilevel inheritance, a class inherits from a child class or derived class.
Suppose three classes A, B, C. A is the superclass, B is the child class of A, C
is the child class of B. In other words, we can say a chain of
classes is called multilevel inheritance.
Multilevel
Inheritance
MULTILEVEL INHERITANCE :
EXAMPLE
# Base class
class Vehicle:
def Vehicle_info(self):
print('Inside Vehicle class’)
# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class’)
# Child class
class SportsCar(Car):
def sports_car_info(self):
print('Inside SportsCar class’)
MULTILEVEL INHERITANCE :
EXAMPLE
# Create object of SportsCar
s_car = SportsCar()
# access Vehicle's and Car info using SportsCar
object
s_car.Vehicle_info()
s_car.car_info()
s_car.sports_car_info()
Output:
Inside Vehicle class
Inside Car class
Inside SportsCar class
HYBRID INHERITANCE
When inheritance is consists of multiple types or a combination of different
inheritance is called hybrid inheritance.
Hybrid
Inheritance
HYBRID INHERITANCE :
EXAMPLE
class Vehicle:
def vehicle_info(self):
print("Inside Vehicle class")
class Car(Vehicle):
def car_info(self):
print("Inside Car class")
class Truck(Vehicle):
def truck_info(self):
print("Inside Truck class")
# Sports Car can inherits properties of Vehicle and
Car
class SportsCar(Car, Vehicle):
def sports_car_info(self):
HYBRID INHERITANCE :
EXAMPLE
# create object
s_car = SportsCar()
s_car.vehicle_info()
s_car.car_info()
s_car.sports_car_info()
Output:
Inside Vehicle class
Inside Car class
Inside SportsCar class
PYTHON super() FUNCTION
When a class inherits all properties and behavior from the
parent class is called inheritance.
In such a case, the inherited class is a subclass and the latter
class is the parent class.
In child class, we can refer to parent class by using
the super() function.
The super function returns a temporary object of the parent
class that allows us to call a parent class method inside a
child class method.
PYTHON super() FUNCTION :
BENEFITS
1. We are not required to remember or specify the parent class name
to access its
methods.
2. We can use the super() function in both single and multiple
inheritances.
3. The super() function support code reusability as there is no need
to write the
entire function
PYTHON super() FUNCTION :
EXAMPLE
class Company:
def company_name(self):
return 'Google’
class Employee(Company):
def info(self):
# Calling the superclass method using super()function
c_name = super().company_name()
print("Jessa works at", c_name)
# Creating object of child class
Output:
emp = Employee() Jessa works at
[Link]() Google
PYTHON issubclass() FUNCTION
In Python, we can verify whether a particular class is a subclass
of another class.
For this purpose, we can use Python built-in function issubclass().
This function returns True if the given class is the subclass of the
specified class. Otherwise, it returns False.
Syntax:
Where,
issubclass(class, classinfo)
• class: class to be checked.
• classinfo: a class, type, or a tuple of classes or
data types.
PYTHON issubclass() FUNCTION :
EXAMPLE
class Company:
def fun1(self):
print("Inside parent class")
class Employee(Company):
def fun2(self):
print("Inside child class.")
class Player:
def fun3(self):
print("Inside Player class.")
PYTHON issubclass() FUNCTION :
EXAMPLE
# Result True
print(issubclass(Employee, Company))
# Result False
print(issubclass(Employee, list))
# Result False
print(issubclass(Player, Company))
# Result True
print(issubclass(Employee, (list, Company)))
# Result True
print(issubclass(Company, (list, Company)))
class Shape:
def __init__(self, color):
[Link] = color
def draw(self):
return f"Drawing a {[Link]} shape"
class Circle(Shape):
def __init__(self, color, radius):
super().__init__(color)
[Link] = radius
def draw(self):
return f"Drawing a {[Link]} circle with radius {[Link]}"
class Square(Shape):
def __init__(self, color, side_length):
super().__init__(color)
self.side_length = side_length
def draw(self):
return f"Drawing a {[Link]} square with side length {self.side_length}"
# Creating instances of the derived classes
circle_instance = Circle("Red", 5)
square_instance = Square("Blue", 4)
# Accessing attributes and invoking methods
print(circle_instance.draw()) # Output: Drawing a Red circle with radius 5
print(square_instance.draw())
METHOD OVERRIDING
Method Overriding in Python is an OOPs concept closely related to inheritance.
When a child class method overrides(or, provides it's own implementation) the
parent class method of the same name, parameters and return type, it is known as
method overriding.
In this case, the child class's method is called the overriding method and the
parent class's method is called the overridden method.
Method overriding is completely different from the concept of method
overloading. Method overloading occurs when there are two functions with the
same name but different parameters. And, method overloading is not directly
supported in Python.
KEY FEATURE OF METHOD
OVERRIDING
• Method Overriding is derived from the concept of object oriented
programming.
• Method Overriding allows us to change the implementation of a
function in the
child class which is defined in the parent class.
• Method Overriding is a part of the inheritance mechanism.
• Method Overriding avoids duplication of code.
• Method Overriding also enhances the code adding some additional
properties.
PRE-REQUISITE FOR METHOD
OVERRIDING
1. Method overriding cannot be done within a class. So, we need to
derive a child
class from a parent class. Hence Inheritance is mandatory.
2. The method must have the same name as in the parent class.
3. The method must have the same number of parameters as in
the parent
class.
EXAMPLE
no_of_sides is the overriden method
in the Shape class, since the Square
class method - no_of_sides() will
be overriding it (adding it's own
implementation).
two_dimensional is inherited by the
sub_class(hence inherited method)
color is a new method added in the
Square class.
data1 & data2 are
individual properties of the classes.
EXAMPLE
# Parent class
class Shape:
data1 = "abc" # properties
def no_of_sides(self): # function no_of_sides
print("My sides need to be defined. I am from shape class.")
def two_dimensional(self): # function two_dimensional
print("I am a 2D object. I am from shape class")
#Sub-class
class Square(Shape):
data2 = "xyz"
def no_of_sides(self):
print("I have 4 sides. I am from Square class")
def color(self):
print("I have teal color. I am from Square class.")
sq = Square() # Create an object of Square class
sq.no_of_sides() # Override the no_of_sides of parent class
sq.two_dimensional() # Will inherit this method from the parent class
[Link]() # It's own method - color
print("Old value of data1 = ", sq.data1)
sq.data1 = "New value" # Override property of the Parent class
print("The value of data1 in Shape class overridden by the Square class = ", sq.data1)
OUTPUT
I have 4 sides. I am from Square class
I am a 2D object. I am from shape class
I have teal color. I am from Square class.
Old value of data1 = abc
The value of data1 in Shape class overridden by the
Square class = New value
METHOD RESOLUTION ORDER IN
PYTHON
Method resolution order in Python is the order in which a python program resolves
or searches for a class in case of multiple inheritance.
Important points to be noted --
It play's a crucial role for programs using multi-inheritance.
In multi-inheritance a class is derived from more than one base class, hence
inheriting all properties of the base class
In this approach -> the method or attributes are first searched in the base class.
If it is not present then the searching moves a level up -- to the immediate
parent class. And if again no luck, then the searching continues following the
same search approach.
It follows the depth-first search approach.
Note: Diamond Inheritance is a very good example of overriding in multiple
EXAMPLE inheritance in Python.
Scenario 1:
class A:
def demo (self):
print(" From class A")
class B(A):
def demo(self):
print(" From class B")
class C(A):
def demo(self):
print(" From class C")
# To check MRO
Diamond Inheritance
class D(B,C):
def check(self):
print("This is an example showing Method
Resolution order")
Output:
obj = D() [Link]()
From class B
The order of execution will be : class D -> class B -> class C -> class A
EXAMPLE
Scenario 2:
class A:
def demo (self):
print(" From class A")
class B(A):
def demo(self):
print(" From class B")
class C(A):
def demo(self):
print(" From class C")
# To check MRO
Diamond Inheritance
class D(C,B):
def check(self):
print("This is an example showing Method
Resolution order")
Output:
obj = D() [Link]()
From class C
The order of execution will be : class D -> class C -> class B -> class A
EXAMPLE
Scenario 3:
class A:
def demo (self):
print(" From class A")
class B(A):
def demo(self):
print(" From class B")
class C(A):
def demo(self):
print(" From class C")
# To check MRO
class D(A,B,C): Diamond Inheritance
def check(self):
print("This is an example showing Method
Resolution order")
obj = D() Output:
[Link]() Type Error
EXAMPLE
Scenario 3:
class A:
def demo (self):
print(" From class A")
class B(A):
def demo(self):
print(" From class B")
class C(A):
def demo(self):
print(" From class C")
# To check MRO
class D(B,C,A): Diamond Inheritance
def check(self):
print("This is an example showing Method
Resolution order")
obj = D() Output:
[Link]() From Class B
OVERRIDING IN MULTIPLE
INHERITANCE
When a class is derived from one or more parent(base) class,
inheriting all it's properties, it is called the multiple inheritance.
If the child class provides it's own implementation to the
methods/attributes while inheriting them from it's parent/parents
then it is known as Overriding in Multiple Inheritance.
EXAMPLE
class Book: Output:
def subjectName(self): This is a Science Book
print(" This is a generic Book") Hi I'm from book!
def aboutMe(self):
print("Hi I'm from book!")
class Physics (Book):
def subjectName(self):
print(" This is a Physics Book ")
class Chemistry (Book):
def subjectName(self):
print("This is a Chemistry Book")
class Science (Physics, Chemistry):
def subjectName(self):
print("This is a Science Book")
obj = Science()
[Link]() #will execute the method from the class Science
[Link]() #will execute the method from the class Book
OVERRIDING IN MULTILEVEL
INHERITANCE
When we have a child and grandchild relationship in our code
where we have different levels relationship, it is known as Multi-
level Inheritance.
When we override the methods or attributes of the Parent class or
GrandParent class through the child class, then it is known as
Overriding in Multi-level Inheritance.
EXAMPLE
Output:
class GrandFather: This is Mr. A's House
def home (self): Hi I'm 20 years old!
print("This is Mr. A's House")
def age(self):
print("Hi I'm 70 years old!")
class Father(Grandfather):
def age(self):
print("Hi I'm 45 years old!")
class Son(Father):
def age(self):
print("Hi I'm 20 years old!")
obj = Son()
[Link]()
[Link]()
THANK YOU