SlideShare a Scribd company logo
Python Inheritance (BCAC403)
Inheritance is an important aspect of the object-oriented
paradigm. Inheritance provides code reusability to the program
because we can use an existing class to create a new class.
In inheritance, the child class acquires the properties and can
access all the data members and functions defined in the parent
class.
A child class can also provide its specific implementation to the
functions of the parent class.
In python, a derived class can inherit base class by just mentioning the
base in the bracket after the derived class name. Consider the following
syntax to inherit a base class into the derived class.
Syntax:
Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}
Benefits of Inheritance
It represents real-world relationships well.
It provides the reusability of a code. We don’t have to write the
same code again and again.
It is transitive in nature, which means that if class B inherits
from another class A, then all the subclasses of B would
automatically inherit from class A.
Inheritance offers a simple, understandable model structure.
Less development and maintenance expenses result from an
inheritance.
Note:
The process of inheriting the properties of the parent class into a child class is
called inheritance. The main purpose of inheritance is the reusability of code
because we can use the existing class to create a new class instead of creating
it from scratch.
In inheritance, the child class acquires all the data members, properties, and
functions from the parent class. Also, a child class can also provide its specific
implementation to the methods of the parent 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.
Syntax:
class BaseClass:
//Body of base class
{Body}
class DerivedClass(BaseClass):
//Body of derived class
{Body}
Types of Inheritance in Python
1.Single inheritance
2.Multiple Inheritance
3.Multilevel inheritance
4.Hierarchical Inheritance
5.Hybrid Inheritance
1.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.
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
car = Car()
# access Vehicle's info using car object
car.Vehicle_info()
car.car_info()
Output:
Inside Vehicle class
Inside Car class
Example
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()
Output:
dog barking
Animal Speaking
2.Multiple Inheritance:
When a class can be derived from more than one base class this
type of inheritance is called multiple inheritances. In multiple
inheritances, all the features of the base classes are inherited into
the derived class.
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)
# 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
Example:
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
Output:
30
200
0.5
Multilevel Inheritance
In multilevel inheritance, features of the base class and the derived
class are further inherited into the new derived class. This is similar
to a relationship representing a child and a grandfather.
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')
# 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
Example
class Animal:
def speak(self):
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
Output:
dog barking
Animal Speaking
Eating bread...
Hierarchical Inheritance
When more than one derived class are created from a single base
this type of inheritance is called hierarchical inheritance. In this
program, we have a parent (base) class and two child (derived)
classes.
Example
Let’s create ‘Vehicle’ as a parent class and two child class ‘Car’ and ‘Truck’
as a parent class.
class Vehicle:
def info(self):
print("This is Vehicle")
class Car(Vehicle):
def car_info(self, name):
print("Car name is:", name)
class Truck(Vehicle):
def truck_info(self, name):
print("Truck name is:", name)
obj1 = Car()
obj1.info()
obj1.car_info('BMW')
obj2 = Truck()
obj2.info()
obj2.truck_info('Ford')
Output:
This is Vehicle
Car name is: BMW
This is Vehicle
Truck name is: Ford
Hybrid Inheritance
Inheritance consisting of multiple types of inheritance is called
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):
print("Inside SportsCar class")
# 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
Executed in: 0.01 sec(s)
Memory: 4188 kilobyte(s)
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.
Benefits of using the super() function.
We are not required to remember or specify the
parent class name to access its methods.
We can use the super() function in both single and multiple
inheritances.
The super() function support code reusability as there is no
need to write the entire 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
emp = Employee()
emp.info()
Output:
Jessa works at Google
Ad

Recommended

arthimetic operator,classes,objects,instant
arthimetic operator,classes,objects,instant
ssuser77162c
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
Inheritance_in_OOP_using Python Programming
Inheritance_in_OOP_using Python Programming
abigailjudith8
 
Inheritance and polymorphism oops concepts in python
Inheritance and polymorphism oops concepts in python
deepalishinkar1
 
Object oriented Programning Lanuagues in text format.
Object oriented Programning Lanuagues in text format.
SravaniSravani53
 
Inheritance
Inheritance
JayanthiNeelampalli
 
Lecture on Python OP concepts of Polymorpysim and Inheritance.pdf
Lecture on Python OP concepts of Polymorpysim and Inheritance.pdf
waqaskhan428678
 
Class and Objects in python programming.pptx
Class and Objects in python programming.pptx
Rajtherock
 
601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx
srinivasa gowda
 
Inheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptx
MalligaarjunanN
 
Chapter 07 inheritance
Chapter 07 inheritance
Praveen M Jigajinni
 
Python programming computer science and engineering
Python programming computer science and engineering
IRAH34
 
Unit_3_2_INHERITANUnit_3_2_INHERITANCE.pdfCE.pdf
Unit_3_2_INHERITANUnit_3_2_INHERITANCE.pdfCE.pdf
RutviBaraiya
 
inheritance in python with full detail.ppt
inheritance in python with full detail.ppt
ssuser7b0a4d
 
INHERITANCE ppt of python.pptx & PYTHON INHERITANCE PPT
INHERITANCE ppt of python.pptx & PYTHON INHERITANCE PPT
deepuranjankumar08
 
Python inheritance
Python inheritance
ISREducations
 
Problem solving with python programming OOP's Concept
Problem solving with python programming OOP's Concept
rohitsharma24121
 
Inheritance Super and MRO _
Inheritance Super and MRO _
swati463221
 
oops-in-python-240412044200-2d5c6552.pptx
oops-in-python-240412044200-2d5c6552.pptx
anilvarsha1
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHON
Lalitkumar_98
 
Introduction to OOP in python inheritance
Introduction to OOP in python inheritance
Aleksander Fabijan
 
Inheritance in oops
Inheritance in oops
Hirra Sultan
 
Object Oriented Programming.pptx
Object Oriented Programming.pptx
SAICHARANREDDYN
 
Object-Oriented Programming (OO) in pythonP) in python.pptx
Object-Oriented Programming (OO) in pythonP) in python.pptx
institute of Geoinformatics and Earth Observation at PMAS ARID Agriculture University of Rawalpindi
 
OOPS.pptx
OOPS.pptx
NitinSharma134320
 
McMullen_ProgwPython_1e_mod17_PowerPoint.pptx
McMullen_ProgwPython_1e_mod17_PowerPoint.pptx
tlui
 
Inheritance
Inheritance
prashant prath
 
python1 object oriented programming.pptx
python1 object oriented programming.pptx
PravinBhargav1
 
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
HistoPathology Ppt. Arshita Gupta for Diploma
HistoPathology Ppt. Arshita Gupta for Diploma
arshitagupta674
 

More Related Content

Similar to All about python Inheritance.python codingdf (20)

601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx
srinivasa gowda
 
Inheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptx
MalligaarjunanN
 
Chapter 07 inheritance
Chapter 07 inheritance
Praveen M Jigajinni
 
Python programming computer science and engineering
Python programming computer science and engineering
IRAH34
 
Unit_3_2_INHERITANUnit_3_2_INHERITANCE.pdfCE.pdf
Unit_3_2_INHERITANUnit_3_2_INHERITANCE.pdfCE.pdf
RutviBaraiya
 
inheritance in python with full detail.ppt
inheritance in python with full detail.ppt
ssuser7b0a4d
 
INHERITANCE ppt of python.pptx & PYTHON INHERITANCE PPT
INHERITANCE ppt of python.pptx & PYTHON INHERITANCE PPT
deepuranjankumar08
 
Python inheritance
Python inheritance
ISREducations
 
Problem solving with python programming OOP's Concept
Problem solving with python programming OOP's Concept
rohitsharma24121
 
Inheritance Super and MRO _
Inheritance Super and MRO _
swati463221
 
oops-in-python-240412044200-2d5c6552.pptx
oops-in-python-240412044200-2d5c6552.pptx
anilvarsha1
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHON
Lalitkumar_98
 
Introduction to OOP in python inheritance
Introduction to OOP in python inheritance
Aleksander Fabijan
 
Inheritance in oops
Inheritance in oops
Hirra Sultan
 
Object Oriented Programming.pptx
Object Oriented Programming.pptx
SAICHARANREDDYN
 
Object-Oriented Programming (OO) in pythonP) in python.pptx
Object-Oriented Programming (OO) in pythonP) in python.pptx
institute of Geoinformatics and Earth Observation at PMAS ARID Agriculture University of Rawalpindi
 
OOPS.pptx
OOPS.pptx
NitinSharma134320
 
McMullen_ProgwPython_1e_mod17_PowerPoint.pptx
McMullen_ProgwPython_1e_mod17_PowerPoint.pptx
tlui
 
Inheritance
Inheritance
prashant prath
 
python1 object oriented programming.pptx
python1 object oriented programming.pptx
PravinBhargav1
 
601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx
srinivasa gowda
 
Inheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptx
MalligaarjunanN
 
Python programming computer science and engineering
Python programming computer science and engineering
IRAH34
 
Unit_3_2_INHERITANUnit_3_2_INHERITANCE.pdfCE.pdf
Unit_3_2_INHERITANUnit_3_2_INHERITANCE.pdfCE.pdf
RutviBaraiya
 
inheritance in python with full detail.ppt
inheritance in python with full detail.ppt
ssuser7b0a4d
 
INHERITANCE ppt of python.pptx & PYTHON INHERITANCE PPT
INHERITANCE ppt of python.pptx & PYTHON INHERITANCE PPT
deepuranjankumar08
 
Problem solving with python programming OOP's Concept
Problem solving with python programming OOP's Concept
rohitsharma24121
 
Inheritance Super and MRO _
Inheritance Super and MRO _
swati463221
 
oops-in-python-240412044200-2d5c6552.pptx
oops-in-python-240412044200-2d5c6552.pptx
anilvarsha1
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHON
Lalitkumar_98
 
Introduction to OOP in python inheritance
Introduction to OOP in python inheritance
Aleksander Fabijan
 
Inheritance in oops
Inheritance in oops
Hirra Sultan
 
Object Oriented Programming.pptx
Object Oriented Programming.pptx
SAICHARANREDDYN
 
McMullen_ProgwPython_1e_mod17_PowerPoint.pptx
McMullen_ProgwPython_1e_mod17_PowerPoint.pptx
tlui
 
python1 object oriented programming.pptx
python1 object oriented programming.pptx
PravinBhargav1
 

Recently uploaded (20)

IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
HistoPathology Ppt. Arshita Gupta for Diploma
HistoPathology Ppt. Arshita Gupta for Diploma
arshitagupta674
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
Paper 106 | Ambition and Corruption: A Comparative Analysis of ‘The Great Gat...
Paper 106 | Ambition and Corruption: A Comparative Analysis of ‘The Great Gat...
Rajdeep Bavaliya
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
LDMMIA Shop & Student News Summer Solstice 25
LDMMIA Shop & Student News Summer Solstice 25
LDM & Mia eStudios
 
Values Education 10 Quarter 1 Module .pptx
Values Education 10 Quarter 1 Module .pptx
JBPafin
 
Peer Teaching Observations During School Internship
Peer Teaching Observations During School Internship
AjayaMohanty7
 
How payment terms are configured in Odoo 18
How payment terms are configured in Odoo 18
Celine George
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
Q1_TLE 8_Week 1- Day 1 tools and equipment
Q1_TLE 8_Week 1- Day 1 tools and equipment
clairenotado3
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
How to Customize Quotation Layouts in Odoo 18
How to Customize Quotation Layouts in Odoo 18
Celine George
 
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
This is why students from these 44 institutions have not received National Se...
This is why students from these 44 institutions have not received National Se...
Kweku Zurek
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
VCE Literature Section A Exam Response Guide
VCE Literature Section A Exam Response Guide
jpinnuck
 
Vitamin and Nutritional Deficiencies.pptx
Vitamin and Nutritional Deficiencies.pptx
Vishal Chanalia
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
June 2025 Progress Update With Board Call_In process.pptx
June 2025 Progress Update With Board Call_In process.pptx
International Society of Service Innovation Professionals
 
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT KGP Quiz Week 2024 Sports Quiz (Prelims + Finals)
IIT Kharagpur Quiz Club
 
HistoPathology Ppt. Arshita Gupta for Diploma
HistoPathology Ppt. Arshita Gupta for Diploma
arshitagupta674
 
English 3 Quarter 1_LEwithLAS_Week 1.pdf
English 3 Quarter 1_LEwithLAS_Week 1.pdf
DeAsisAlyanajaneH
 
Paper 106 | Ambition and Corruption: A Comparative Analysis of ‘The Great Gat...
Paper 106 | Ambition and Corruption: A Comparative Analysis of ‘The Great Gat...
Rajdeep Bavaliya
 
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
SCHIZOPHRENIA OTHER PSYCHOTIC DISORDER LIKE Persistent delusion/Capgras syndr...
parmarjuli1412
 
LDMMIA Shop & Student News Summer Solstice 25
LDMMIA Shop & Student News Summer Solstice 25
LDM & Mia eStudios
 
Values Education 10 Quarter 1 Module .pptx
Values Education 10 Quarter 1 Module .pptx
JBPafin
 
Peer Teaching Observations During School Internship
Peer Teaching Observations During School Internship
AjayaMohanty7
 
How payment terms are configured in Odoo 18
How payment terms are configured in Odoo 18
Celine George
 
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
M&A5 Q1 1 differentiate evolving early Philippine conventional and contempora...
ErlizaRosete
 
Q1_TLE 8_Week 1- Day 1 tools and equipment
Q1_TLE 8_Week 1- Day 1 tools and equipment
clairenotado3
 
Tanja Vujicic - PISA for Schools contact Info
Tanja Vujicic - PISA for Schools contact Info
EduSkills OECD
 
How to Customize Quotation Layouts in Odoo 18
How to Customize Quotation Layouts in Odoo 18
Celine George
 
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
Public Health For The 21st Century 1st Edition Judy Orme Jane Powell
trjnesjnqg7801
 
This is why students from these 44 institutions have not received National Se...
This is why students from these 44 institutions have not received National Se...
Kweku Zurek
 
List View Components in Odoo 18 - Odoo Slides
List View Components in Odoo 18 - Odoo Slides
Celine George
 
VCE Literature Section A Exam Response Guide
VCE Literature Section A Exam Response Guide
jpinnuck
 
Vitamin and Nutritional Deficiencies.pptx
Vitamin and Nutritional Deficiencies.pptx
Vishal Chanalia
 
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
ECONOMICS, DISASTER MANAGEMENT, ROAD SAFETY - STUDY MATERIAL [10TH]
SHERAZ AHMAD LONE
 
Ad

All about python Inheritance.python codingdf

  • 1. Python Inheritance (BCAC403) Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code reusability to the program because we can use an existing class to create a new class. In inheritance, the child class acquires the properties and can access all the data members and functions defined in the parent class. A child class can also provide its specific implementation to the functions of the parent class.
  • 2. In python, a derived class can inherit base class by just mentioning the base in the bracket after the derived class name. Consider the following syntax to inherit a base class into the derived class. Syntax: Class BaseClass: {Body} Class DerivedClass(BaseClass): {Body}
  • 3. Benefits of Inheritance It represents real-world relationships well. It provides the reusability of a code. We don’t have to write the same code again and again. It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A. Inheritance offers a simple, understandable model structure. Less development and maintenance expenses result from an inheritance.
  • 4. Note: The process of inheriting the properties of the parent class into a child class is called inheritance. The main purpose of inheritance is the reusability of code because we can use the existing class to create a new class instead of creating it from scratch. In inheritance, the child class acquires all the data members, properties, and functions from the parent class. Also, a child class can also provide its specific implementation to the methods of the parent 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. Syntax: class BaseClass: //Body of base class {Body} class DerivedClass(BaseClass): //Body of derived class {Body}
  • 5. Types of Inheritance in Python 1.Single inheritance 2.Multiple Inheritance 3.Multilevel inheritance 4.Hierarchical Inheritance 5.Hybrid Inheritance
  • 6. 1.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.
  • 7. 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 car = Car() # access Vehicle's info using car object car.Vehicle_info() car.car_info() Output: Inside Vehicle class Inside Car class
  • 8. Example class Animal: def speak(self): print("Animal Speaking") #child class Dog inherits the base class Animal class Dog(Animal): def bark(self): print("dog barking") d = Dog() d.bark() d.speak() Output: dog barking Animal Speaking
  • 9. 2.Multiple Inheritance: When a class can be derived from more than one base class this type of inheritance is called multiple inheritances. In multiple inheritances, all the features of the base classes are inherited into the derived class.
  • 10. 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) # Create object of Employee emp = Employee() # access data emp.person_info('Jessa‘, 28) emp.company_info('Google', 'Atlanta') emp.Employee_info(12000, 'Machine Learning')
  • 11. Output: Inside Person class Name: Jessa Age: 28 Inside Company class Name: Google location: Atlanta Inside Employee class Salary: 12000 Skill: Machine Learning
  • 12. Example: class Calculation1: def Summation(self,a,b): return a+b; class Calculation2: def Multiplication(self,a,b): return a*b; class Derived(Calculation1,Calculation2): def Divide(self,a,b): return a/b; d = Derived() print(d.Summation(10,20)) print(d.Multiplication(10,20)) print(d.Divide(10,20)) Output: 30 200 0.5
  • 13. Multilevel Inheritance In multilevel inheritance, features of the base class and the derived class are further inherited into the new derived class. This is similar to a relationship representing a child and a grandfather.
  • 14. 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') # 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()
  • 15. Output: Inside Vehicle class Inside Car class Inside SportsCar class
  • 16. Example class Animal: def speak(self): print("Animal Speaking") #The child class Dog inherits the base class Animal class Dog(Animal): def bark(self): print("dog barking") #The child class Dogchild inherits another child class Dog class DogChild(Dog): def eat(self): print("Eating bread...") d = DogChild() d.bark() d.speak() d.eat() Output: dog barking Animal Speaking Eating bread...
  • 17. Hierarchical Inheritance When more than one derived class are created from a single base this type of inheritance is called hierarchical inheritance. In this program, we have a parent (base) class and two child (derived) classes.
  • 18. Example Let’s create ‘Vehicle’ as a parent class and two child class ‘Car’ and ‘Truck’ as a parent class. class Vehicle: def info(self): print("This is Vehicle") class Car(Vehicle): def car_info(self, name): print("Car name is:", name) class Truck(Vehicle): def truck_info(self, name): print("Truck name is:", name) obj1 = Car() obj1.info() obj1.car_info('BMW') obj2 = Truck() obj2.info() obj2.truck_info('Ford')
  • 19. Output: This is Vehicle Car name is: BMW This is Vehicle Truck name is: Ford
  • 20. Hybrid Inheritance Inheritance consisting of multiple types of inheritance is called hybrid inheritance.
  • 21. 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): print("Inside SportsCar class") # create object s_car = SportsCar() s_car.vehicle_info() s_car.car_info() s_car.sports_car_info()
  • 22. Output : Inside Vehicle class Inside Car class Inside SportsCar class Executed in: 0.01 sec(s) Memory: 4188 kilobyte(s)
  • 23. 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.
  • 24. Benefits of using the super() function. We are not required to remember or specify the parent class name to access its methods. We can use the super() function in both single and multiple inheritances. The super() function support code reusability as there is no need to write the entire function
  • 25. 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 emp = Employee() emp.info() Output: Jessa works at Google