SlideShare a Scribd company logo
Inheritance isthe capabilityof one classtoderive orinheritthe propertiesfromanotherclass.The benefitsof
inheritance are:
It representsreal-worldrelationshipswell.
It providesreusabilityof acode.We don’thave to write the same code againand again.Also,itallowsusto add
more featurestoa class withoutmodifyingit.
It istransitive innature,whichmeansthatif classB inheritsfromanotherclassA,thenall the subclassesof B would
automaticallyinheritfromclassA.
# A Pythonprogram to demonstrate inheritance
# Base or Superclass.Note objectinbracket.
# (Generally,objectismade ancestorof all classes)
# InPython3.x "classPerson"is
# equivalentto"classPerson(object)"
classPerson(object):
# Constructor
def __init__(self,name):
self.name=name
# To get name
def getName(self):
returnself.name
# To checkif thispersonisan employee
def isEmployee(self):
returnFalse
# InheritedorSubclass(Note Personinbracket)
classEmployee(Person):
# Here we returntrue
def isEmployee(self):
returnTrue
# Drivercode
emp= Person("Geek1") # AnObjectof Person
print(emp.getName(),emp.isEmployee())
emp= Employee("Geek2") #An Objectof Employee
print(emp.getName(),emp.isEmployee())
==============
Subclassing(Callingconstructorof parentclass)
A childclassneedstoidentifywhichclassisitsparentclass.Thiscan be done bymentioningthe parent classname in
the definitionof the childclass.
Eg: class subclass_name (superclass_name):
_ _ _
_ _ _
# Pythoncode to demonstrate howparentconstructors
# are called.
# parentclass
classPerson( object):
# __init__ isknownas the constructor
def __init__(self,name,idnumber):
self.name =name
self.idnumber=idnumber
def display(self):
print(self.name)
print(self.idnumber)
# childclass
classEmployee( Person):
def __init__(self,name,idnumber,salary,post):
self.salary=salary
self.post=post
# invokingthe __init__of the parentclass
Person.__init__(self,name,idnumber)
# creationof an objectvariable oran instance
a = Employee('Rahul',886012, 200000, "Intern")
# callingafunctionof the class Personusingitsinstance
a.display()
====
Differentformsof Inheritance:
1. Single inheritance:Whenachildclassinheritsfromonlyone parentclass,itiscalledsingle inheritance.We sawan
example above.
2. Multiple inheritance:Whenachildclassinheritsfrommultipleparentclasses,itiscalledmultiple inheritance.
Unlike Javaand like C++,Pythonsupportsmultipleinheritance.We specifyall parentclassesasacomma-separated
listinthe bracket.
# Pythonexampletoshowthe workingof multiple
# inheritance
classBase1(object):
def __init__(self):
self.str1="Geek1"
print("Base1")
classBase2(object):
def __init__(self):
self.str2="Geek2"
print("Base2")
classDerived(Base1,Base2):
def __init__(self):
# Callingconstructorsof Base1
# and Base2 classes
Base1.__init__(self)
Base2.__init__(self)
print("Derived")
def printStrs(self):
print(self.str1,self.str2)
ob = Derived()
ob.printStrs()
=======
3. Multilevel inheritance:Whenwe have achildand grandchild relationship.
# A Pythonprogramto demonstrate inheritance
# Base or Superclass.Note objectinbracket.
# (Generally,objectismade ancestorof all classes)
# InPython3.x "classPerson"is
# equivalentto"classPerson(object)"
classBase(object):
# Constructor
def __init__(self,name):
self.name=name
# To get name
def getName(self):
returnself.name
# InheritedorSubclass(Note Personinbracket)
classChild(Base):
# Constructor
def __init__(self,name,age):
Base.__init__(self,name)
self.age =age
# To get name
def getAge(self):
returnself.age
# InheritedorSubclass(Note Personinbracket)
classGrandChild(Child):
# Constructor
def __init__(self,name,age,address):
Child.__init__(self,name,age)
self.address=address
# To get address
def getAddress(self):
returnself.address
# Drivercode
g = GrandChild("Geek1",23,"Noida")
print(g.getName(), g.getAge(),g.getAddress())

More Related Content

What's hot (14)

PPTX
Dynamic Polymorphism in C++
Dharmisha Sharma
 
DOCX
C# note
Dr. Somnath Sinha
 
PPTX
ICPC Demo
Patricia Deshane
 
PDF
Python master class part 1
Chathuranga Bandara
 
PPTX
polymorphism
Imtiaz Hussain
 
PPTX
PhD Dissertation
Patricia Deshane
 
PPT
C++ classes tutorials
akreyi
 
PDF
Python master class 2
Chathuranga Bandara
 
PDF
Kotlin으로 안드로이드 개발하기
Taehwan kwon
 
PPT
Static and Dynamic polymorphism in C++
Anil Bapat
 
PPTX
Polymorphism and its types
Suraj Bora
 
PPT
Douglas Crockford Presentation Goodparts
Ajax Experience 2009
 
PPTX
Introduction to TypeScript
KeithMurgic
 
PDF
JDD2015: Frege - how to program with pure functions - Dierk König
PROIDEA
 
Dynamic Polymorphism in C++
Dharmisha Sharma
 
ICPC Demo
Patricia Deshane
 
Python master class part 1
Chathuranga Bandara
 
polymorphism
Imtiaz Hussain
 
PhD Dissertation
Patricia Deshane
 
C++ classes tutorials
akreyi
 
Python master class 2
Chathuranga Bandara
 
Kotlin으로 안드로이드 개발하기
Taehwan kwon
 
Static and Dynamic polymorphism in C++
Anil Bapat
 
Polymorphism and its types
Suraj Bora
 
Douglas Crockford Presentation Goodparts
Ajax Experience 2009
 
Introduction to TypeScript
KeithMurgic
 
JDD2015: Frege - how to program with pure functions - Dierk König
PROIDEA
 

Similar to Python inheritance (20)

PDF
All about python Inheritance.python codingdf
adipapai181023
 
PPTX
Chapter 07 inheritance
Praveen M Jigajinni
 
PDF
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
PDF
Inheritance and polymorphism oops concepts in python
deepalishinkar1
 
PPTX
Inheritance_in_OOP_using Python Programming
abigailjudith8
 
PDF
Lecture on Python OP concepts of Polymorpysim and Inheritance.pdf
waqaskhan428678
 
PPTX
arthimetic operator,classes,objects,instant
ssuser77162c
 
PPTX
Inheritance_Polymorphism_Overloading_overriding.pptx
MalligaarjunanN
 
PDF
Unit_3_2_INHERITANUnit_3_2_INHERITANCE.pdfCE.pdf
RutviBaraiya
 
PPTX
Inheritance
JayanthiNeelampalli
 
PDF
Unit 3-Classes ,Objects and Inheritance.pdf
Harsha Patil
 
PPTX
Problem solving with python programming OOP's Concept
rohitsharma24121
 
PDF
Object oriented Programning Lanuagues in text format.
SravaniSravani53
 
PPTX
Class and Objects in python programming.pptx
Rajtherock
 
PPTX
INHERITANCE ppt of python.pptx & PYTHON INHERITANCE PPT
deepuranjankumar08
 
ODP
Inheritance
Pradhan Rishi Sharma
 
PDF
Inheritance
Pradhan Rishi Sharma
 
PPT
Module 4 Effect of Reuse on using Inheritance.ppt
ramlingams
 
PPTX
Inheritance in oops
Hirra Sultan
 
PPTX
Python: Basic Inheritance
Damian T. Gordon
 
All about python Inheritance.python codingdf
adipapai181023
 
Chapter 07 inheritance
Praveen M Jigajinni
 
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
Inheritance and polymorphism oops concepts in python
deepalishinkar1
 
Inheritance_in_OOP_using Python Programming
abigailjudith8
 
Lecture on Python OP concepts of Polymorpysim and Inheritance.pdf
waqaskhan428678
 
arthimetic operator,classes,objects,instant
ssuser77162c
 
Inheritance_Polymorphism_Overloading_overriding.pptx
MalligaarjunanN
 
Unit_3_2_INHERITANUnit_3_2_INHERITANCE.pdfCE.pdf
RutviBaraiya
 
Inheritance
JayanthiNeelampalli
 
Unit 3-Classes ,Objects and Inheritance.pdf
Harsha Patil
 
Problem solving with python programming OOP's Concept
rohitsharma24121
 
Object oriented Programning Lanuagues in text format.
SravaniSravani53
 
Class and Objects in python programming.pptx
Rajtherock
 
INHERITANCE ppt of python.pptx & PYTHON INHERITANCE PPT
deepuranjankumar08
 
Module 4 Effect of Reuse on using Inheritance.ppt
ramlingams
 
Inheritance in oops
Hirra Sultan
 
Python: Basic Inheritance
Damian T. Gordon
 
Ad

Recently uploaded (20)

PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
Controller Request and Response in Odoo18
Celine George
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Controller Request and Response in Odoo18
Celine George
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Dimensions of Societal Planning in Commonism
StefanMz
 
Ad

Python inheritance

  • 1. Inheritance isthe capabilityof one classtoderive orinheritthe propertiesfromanotherclass.The benefitsof inheritance are: It representsreal-worldrelationshipswell. It providesreusabilityof acode.We don’thave to write the same code againand again.Also,itallowsusto add more featurestoa class withoutmodifyingit. It istransitive innature,whichmeansthatif classB inheritsfromanotherclassA,thenall the subclassesof B would automaticallyinheritfromclassA. # A Pythonprogram to demonstrate inheritance # Base or Superclass.Note objectinbracket. # (Generally,objectismade ancestorof all classes) # InPython3.x "classPerson"is # equivalentto"classPerson(object)" classPerson(object): # Constructor def __init__(self,name): self.name=name # To get name def getName(self): returnself.name # To checkif thispersonisan employee def isEmployee(self): returnFalse # InheritedorSubclass(Note Personinbracket) classEmployee(Person): # Here we returntrue def isEmployee(self): returnTrue # Drivercode emp= Person("Geek1") # AnObjectof Person print(emp.getName(),emp.isEmployee()) emp= Employee("Geek2") #An Objectof Employee print(emp.getName(),emp.isEmployee())
  • 2. ============== Subclassing(Callingconstructorof parentclass) A childclassneedstoidentifywhichclassisitsparentclass.Thiscan be done bymentioningthe parent classname in the definitionof the childclass. Eg: class subclass_name (superclass_name): _ _ _ _ _ _ # Pythoncode to demonstrate howparentconstructors # are called. # parentclass classPerson( object): # __init__ isknownas the constructor def __init__(self,name,idnumber): self.name =name self.idnumber=idnumber def display(self): print(self.name) print(self.idnumber) # childclass classEmployee( Person): def __init__(self,name,idnumber,salary,post): self.salary=salary self.post=post # invokingthe __init__of the parentclass Person.__init__(self,name,idnumber) # creationof an objectvariable oran instance a = Employee('Rahul',886012, 200000, "Intern") # callingafunctionof the class Personusingitsinstance a.display() ==== Differentformsof Inheritance: 1. Single inheritance:Whenachildclassinheritsfromonlyone parentclass,itiscalledsingle inheritance.We sawan example above.
  • 3. 2. Multiple inheritance:Whenachildclassinheritsfrommultipleparentclasses,itiscalledmultiple inheritance. Unlike Javaand like C++,Pythonsupportsmultipleinheritance.We specifyall parentclassesasacomma-separated listinthe bracket. # Pythonexampletoshowthe workingof multiple # inheritance classBase1(object): def __init__(self): self.str1="Geek1" print("Base1") classBase2(object): def __init__(self): self.str2="Geek2" print("Base2") classDerived(Base1,Base2): def __init__(self): # Callingconstructorsof Base1 # and Base2 classes Base1.__init__(self) Base2.__init__(self) print("Derived") def printStrs(self): print(self.str1,self.str2) ob = Derived() ob.printStrs() ======= 3. Multilevel inheritance:Whenwe have achildand grandchild relationship. # A Pythonprogramto demonstrate inheritance # Base or Superclass.Note objectinbracket. # (Generally,objectismade ancestorof all classes) # InPython3.x "classPerson"is # equivalentto"classPerson(object)" classBase(object): # Constructor
  • 4. def __init__(self,name): self.name=name # To get name def getName(self): returnself.name # InheritedorSubclass(Note Personinbracket) classChild(Base): # Constructor def __init__(self,name,age): Base.__init__(self,name) self.age =age # To get name def getAge(self): returnself.age # InheritedorSubclass(Note Personinbracket) classGrandChild(Child): # Constructor def __init__(self,name,age,address): Child.__init__(self,name,age) self.address=address # To get address def getAddress(self): returnself.address # Drivercode g = GrandChild("Geek1",23,"Noida") print(g.getName(), g.getAge(),g.getAddress())