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

More Related Content

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

601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx
srinivasa gowda
 
Inheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptxInheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptx
MalligaarjunanN
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
Praveen M Jigajinni
 
Python programming computer science and engineering
Python programming computer science and engineeringPython 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.pdfUnit_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.pptinheritance 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 PPTINHERITANCE ppt of python.pptx & PYTHON INHERITANCE PPT
INHERITANCE ppt of python.pptx & PYTHON INHERITANCE PPT
deepuranjankumar08
 
Python inheritance
Python inheritancePython inheritance
Python inheritance
ISREducations
 
Problem solving with python programming OOP's Concept
Problem solving with python programming OOP's ConceptProblem solving with python programming OOP's Concept
Problem solving with python programming OOP's Concept
rohitsharma24121
 
Inheritance Super and MRO _
Inheritance Super and MRO               _Inheritance Super and MRO               _
Inheritance Super and MRO _
swati463221
 
oops-in-python-240412044200-2d5c6552.pptx
oops-in-python-240412044200-2d5c6552.pptxoops-in-python-240412044200-2d5c6552.pptx
oops-in-python-240412044200-2d5c6552.pptx
anilvarsha1
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHON
Lalitkumar_98
 
Introduction to OOP in python inheritance
Introduction to OOP in python   inheritanceIntroduction to OOP in python   inheritance
Introduction to OOP in python inheritance
Aleksander Fabijan
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
Hirra Sultan
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject 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.pptxObject-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.pptxOOPS.pptx
OOPS.pptx
NitinSharma134320
 
McMullen_ProgwPython_1e_mod17_PowerPoint.pptx
McMullen_ProgwPython_1e_mod17_PowerPoint.pptxMcMullen_ProgwPython_1e_mod17_PowerPoint.pptx
McMullen_ProgwPython_1e_mod17_PowerPoint.pptx
tlui
 
Inheritance
InheritanceInheritance
Inheritance
prashant prath
 
python1 object oriented programming.pptx
python1 object oriented programming.pptxpython1 object oriented programming.pptx
python1 object oriented programming.pptx
PravinBhargav1
 
601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx
srinivasa gowda
 
Inheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptxInheritance_Polymorphism_Overloading_overriding.pptx
Inheritance_Polymorphism_Overloading_overriding.pptx
MalligaarjunanN
 
Python programming computer science and engineering
Python programming computer science and engineeringPython 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.pdfUnit_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.pptinheritance 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 PPTINHERITANCE 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 ConceptProblem solving with python programming OOP's Concept
Problem solving with python programming OOP's Concept
rohitsharma24121
 
Inheritance Super and MRO _
Inheritance Super and MRO               _Inheritance Super and MRO               _
Inheritance Super and MRO _
swati463221
 
oops-in-python-240412044200-2d5c6552.pptx
oops-in-python-240412044200-2d5c6552.pptxoops-in-python-240412044200-2d5c6552.pptx
oops-in-python-240412044200-2d5c6552.pptx
anilvarsha1
 
CLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHONCLASS OBJECT AND INHERITANCE IN PYTHON
CLASS OBJECT AND INHERITANCE IN PYTHON
Lalitkumar_98
 
Introduction to OOP in python inheritance
Introduction to OOP in python   inheritanceIntroduction to OOP in python   inheritance
Introduction to OOP in python inheritance
Aleksander Fabijan
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
Hirra Sultan
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptx
SAICHARANREDDYN
 
McMullen_ProgwPython_1e_mod17_PowerPoint.pptx
McMullen_ProgwPython_1e_mod17_PowerPoint.pptxMcMullen_ProgwPython_1e_mod17_PowerPoint.pptx
McMullen_ProgwPython_1e_mod17_PowerPoint.pptx
tlui
 
python1 object oriented programming.pptx
python1 object oriented programming.pptxpython1 object oriented programming.pptx
python1 object oriented programming.pptx
PravinBhargav1
 

Recently uploaded (20)

Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
National Information Standards Organization (NISO)
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptxPests of Rice: Damage, Identification, Life history, and Management.pptx
Pests of Rice: Damage, Identification, Life history, and Management.pptx
Arshad Shaikh
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
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