BCS-DS-427B: PYTHON
Ms. Swati Hans
Assistant Professor, CSE
Manav Rachna International Institute of Research and Studies, Faridabad
1
PYTHON
Unit-4
INHERITANCE, ITS
TYPES
INHERITANCE
Inheritance is the capability of one class to derive or inherit the properties
from some another class.
Parent class is termed as base class
Child class is also termed as derived class
The benefits of inheritance are:
▪Code reusability
We don’t have to write the same code again and again. Also, it allows us to
add more features to a class without modifying it.
▪Transitivity
It means that if class B inherits from another class A, then all the subclasses
of B would automatically inherit from class A.
SINGLE LEVEL INHERITANCE
When a child class inherits from only
one parent class which is not derived
from any other class, it is called as
single level inheritance.
Here A is a base class, B is child class of
A as it is inheriting features of A
class.55d xc ./
+
A
B
SINGLE LEVEL INHERITANCE
CODE
class A:
def funA(self):
print("in A")
class B(A):
def funB(self):
print("in B")
b1=B()
b1.funA
b1.funB()
Here,B class is inheriting class A .So class A
functions will
Become members of class B.
So,when object b1 of class B is created, all
functions of
Class A and B are called from it.
MULTILEVEL INHERITANCE
Multi-level inheritance is when a
derived class inherits another derived
class. There is no limit on the number
of levels up to which, the multi-level
inheritance can be achieved.
Here Person is a base class, Employee
is child class of Person and Manager is
a child class of Employee.
Person
Employee
Manager
MULTILEVEL INHERITANCE
CODE
class Person:
name=""
def getName(self): # To get
name
return self.name
def setName(self,s): # To set
the name
self.name=s
class Manager(Employee):
projectstatus=""
def getProjectStatus(self): # To get
project status
return self.projectstatus
def setProjectStatus(self,st): # To set
project status
self.projectstatus=st
Here,we created three classes
Employee class is inheriting Person class and
Manager class
is inheriting Employee class.
class Employee(Person):
salary=0
def getSalary(self): # To get
salary
return self.salary
def setSalary(self,num): # To set
#Python Program to depict multilevel inheritance
MULTILEVEL CONTINUE…..
Output
m=Manager()
m.setName("Rahul") # calling its setter methods to initialize variables
m.setSalary(155000)
m.setProjectStatus("Half completed")
print("Name is ",m.getName()) # calling all getter functions
print("Salary is ",m.getSalary())
print("Project status is ",m.getProjectStatus())
Creating object of child class and calling its functions
MULTIPLE INHERITANCE
When child class inherits
features of more than
one base class.
Here ,Spacecraft is a child
class
which inherits Antennas
and Power Base classes
Antennas Power
Spacecraft
MULTIPLE INHERITANCE CODE
class Power:
solarcells=0
nickelbattery=0
def setcells_battery(self,a,b):
self.solarcells=a
self.nickelbattery=b
class Spacecraft(Antennas,Power):
mission=''
speed=0
def setMission(self,x):
self.mission=x
def setSpeed(self,y):
self.speed=y
def display(self):
print("Mission is",self.mission)
print("Speed is",self.speed)
print("Antenna diameter
is",self.diameter)
print("Solarcells are ",self.solarcells)
print("Nickle batteries are",
class Antennas:
diameter=0
def setDiameter(self,a):
self.diameter=a
# Python Program to depict multiple inheritance
MULTIPLE INHERITANCE EXAMPLE CODE…
s1 = Spacecraft() # creating space craft object
s1.setMission("Weather Forecasting") # call its setter methods t initialize variables
s1.setSpeed(61000)
s1.setDiameter(6)
s1.setcells_battery(3200,2)
s1.display() # call its display method
Outp
ut
Creating object of child class and calling its functions
USING SUPER() TO CALL
PARENT CLASS CONSTRUCTOR
Any child class can call constructor i.e __init__(..) of parent class i.e Super
class by making use of super.
Syntax:
super().__init__(parameters of base class constructor)
For example, In case of multilevel inheritance ,if A B C
🡪 🡪
If A is parent of B and B is parent of C,Then C can call constructor of B
using siuper and B can call constructor of A using super
EXAMPLE: USING SUPER() IN MULTILEVEL
INHERITANCE
class Vehicle:
vnum=0
def __init__(self,x):
self.vnum=x
def vdisplay(self):
print("Vehicle Number: ",self.vnum)
Vehicle
Car
BulletCar
BulletCar calling Car
constructor using
super()
Car calling Vehicle
constructor using
super()
class Car(Vehicle):
engine=""
def __init__(self,s,n):
self.engine=s
super().__init__(n)
def cdisplay(self):
print("Car engine:",self.engine)
EXAMPLE CONTINUED
class BulletCar(Car):
company=""
def __init__(self,c,s,n):
self.company=c
super().__init__(s,n) #calling Car constructor
def bcardisplay(self):
print("Bullet Car Company :",self.company)
Outp
ut
As ,init() of BulletCar is calling init() of Car
As, Init() of Car is calling init() of Vehicle
When we create obj of BulletCar() ,its init
will
be called automatically.Those constructors
will be
called in sequence
BulletCar init() Car init() Vehicle init().
🡪 🡪
Functions of all parent classes can be
called from
obj=BulletCar("JCBL","Diesel","HR1809“)
# object created
obj.vdisplay() # Vehicle function called
obj.cdisplay() # Car function called
obj.bcardisplay() #BulletCar function called
MRO(METHOD RESOLUTION ORDER)
I
Method Resolution Order (MRO) is the order in which Python looks for a method in a hierarchy of
classes. Especially it plays vital role in the context of multiple inheritance as single method may be
found in multiple super classes.
In the multiple inheritance scenario, any specified attribute is searched first in the current class.
If not found, the search continues into parent classes in depth-first, left-right fashion without
searching same class twice and then finally in object class. As every class in Python is derived
from the class object.
So, In above example , MRO will be
GermanShephard, Dog, GoodAnimals, Object
Dog GoodAnimals
GermanShepar
d
MRO OF A CLASS(In case of Multiple Inheritance):
class GoodAnimals(object):
def __init__(self):
print("They're all good dogs")
super().__init__()
class GermanShepard(Dog,GoodAnimals):
def __init__(self):
print("init GermanShepard")
super().__init__() # calling base class
constructor
obj = GermanShepard()
print(GermanShephard.__mro__)
print(GermanShephard.mro())
MRO of a class can be viewed by using __mro__ attribute or mro() method. Create class Dog,GoodAnimals
, GermanShephard inherits Dog and Goodanimals. Then display MRO of GermanShephard
class Dog:
def __init__(self):
print("init Dog")
super().__init__()
MRO IN CASE OF MULTIPLE INHERITANCE
class GoodAnimals(object):
def __init__(self):
print("They're all good dogs")
super().__init__()
class Dog:
def __init__(self):
print("init Dog")
super().__init__() #pass the call to
#next class in
#MRO
class GermanShepard(Dog,GoodAnimals):
def __init__(self):
print("init GermanShepard")
super().__init__() # calling base class
constructor
obj = GermanShepard()
Output
• When the GermanShepard object is created,
MRO searches for __init__() firstly in
GermanShepard itself.
• GermanShepard init is calling super init() will
call
init of next class in MRO i.e. Dog class init
• Dog class init is calling super init() again
which will call
init of next class in MRO i.e. GoodAnimals
class init
In multiple inheritance, if you want constructor of child should call constructor of all
parent classes.
Then all parent and Child classes should call super().__init__()

Inheritance Super and MRO _

  • 1.
    BCS-DS-427B: PYTHON Ms. SwatiHans Assistant Professor, CSE Manav Rachna International Institute of Research and Studies, Faridabad 1
  • 2.
  • 3.
    INHERITANCE Inheritance is thecapability of one class to derive or inherit the properties from some another class. Parent class is termed as base class Child class is also termed as derived class The benefits of inheritance are: ▪Code reusability We don’t have to write the same code again and again. Also, it allows us to add more features to a class without modifying it. ▪Transitivity It means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A.
  • 4.
    SINGLE LEVEL INHERITANCE Whena child class inherits from only one parent class which is not derived from any other class, it is called as single level inheritance. Here A is a base class, B is child class of A as it is inheriting features of A class.55d xc ./ + A B
  • 5.
    SINGLE LEVEL INHERITANCE CODE classA: def funA(self): print("in A") class B(A): def funB(self): print("in B") b1=B() b1.funA b1.funB() Here,B class is inheriting class A .So class A functions will Become members of class B. So,when object b1 of class B is created, all functions of Class A and B are called from it.
  • 6.
    MULTILEVEL INHERITANCE Multi-level inheritanceis when a derived class inherits another derived class. There is no limit on the number of levels up to which, the multi-level inheritance can be achieved. Here Person is a base class, Employee is child class of Person and Manager is a child class of Employee. Person Employee Manager
  • 7.
    MULTILEVEL INHERITANCE CODE class Person: name="" defgetName(self): # To get name return self.name def setName(self,s): # To set the name self.name=s class Manager(Employee): projectstatus="" def getProjectStatus(self): # To get project status return self.projectstatus def setProjectStatus(self,st): # To set project status self.projectstatus=st Here,we created three classes Employee class is inheriting Person class and Manager class is inheriting Employee class. class Employee(Person): salary=0 def getSalary(self): # To get salary return self.salary def setSalary(self,num): # To set #Python Program to depict multilevel inheritance
  • 8.
    MULTILEVEL CONTINUE….. Output m=Manager() m.setName("Rahul") #calling its setter methods to initialize variables m.setSalary(155000) m.setProjectStatus("Half completed") print("Name is ",m.getName()) # calling all getter functions print("Salary is ",m.getSalary()) print("Project status is ",m.getProjectStatus()) Creating object of child class and calling its functions
  • 9.
    MULTIPLE INHERITANCE When childclass inherits features of more than one base class. Here ,Spacecraft is a child class which inherits Antennas and Power Base classes Antennas Power Spacecraft
  • 10.
    MULTIPLE INHERITANCE CODE classPower: solarcells=0 nickelbattery=0 def setcells_battery(self,a,b): self.solarcells=a self.nickelbattery=b class Spacecraft(Antennas,Power): mission='' speed=0 def setMission(self,x): self.mission=x def setSpeed(self,y): self.speed=y def display(self): print("Mission is",self.mission) print("Speed is",self.speed) print("Antenna diameter is",self.diameter) print("Solarcells are ",self.solarcells) print("Nickle batteries are", class Antennas: diameter=0 def setDiameter(self,a): self.diameter=a # Python Program to depict multiple inheritance
  • 11.
    MULTIPLE INHERITANCE EXAMPLECODE… s1 = Spacecraft() # creating space craft object s1.setMission("Weather Forecasting") # call its setter methods t initialize variables s1.setSpeed(61000) s1.setDiameter(6) s1.setcells_battery(3200,2) s1.display() # call its display method Outp ut Creating object of child class and calling its functions
  • 12.
    USING SUPER() TOCALL PARENT CLASS CONSTRUCTOR Any child class can call constructor i.e __init__(..) of parent class i.e Super class by making use of super. Syntax: super().__init__(parameters of base class constructor) For example, In case of multilevel inheritance ,if A B C 🡪 🡪 If A is parent of B and B is parent of C,Then C can call constructor of B using siuper and B can call constructor of A using super
  • 13.
    EXAMPLE: USING SUPER()IN MULTILEVEL INHERITANCE class Vehicle: vnum=0 def __init__(self,x): self.vnum=x def vdisplay(self): print("Vehicle Number: ",self.vnum) Vehicle Car BulletCar BulletCar calling Car constructor using super() Car calling Vehicle constructor using super() class Car(Vehicle): engine="" def __init__(self,s,n): self.engine=s super().__init__(n) def cdisplay(self): print("Car engine:",self.engine)
  • 14.
    EXAMPLE CONTINUED class BulletCar(Car): company="" def__init__(self,c,s,n): self.company=c super().__init__(s,n) #calling Car constructor def bcardisplay(self): print("Bullet Car Company :",self.company) Outp ut As ,init() of BulletCar is calling init() of Car As, Init() of Car is calling init() of Vehicle When we create obj of BulletCar() ,its init will be called automatically.Those constructors will be called in sequence BulletCar init() Car init() Vehicle init(). 🡪 🡪 Functions of all parent classes can be called from obj=BulletCar("JCBL","Diesel","HR1809“) # object created obj.vdisplay() # Vehicle function called obj.cdisplay() # Car function called obj.bcardisplay() #BulletCar function called
  • 15.
    MRO(METHOD RESOLUTION ORDER) I MethodResolution Order (MRO) is the order in which Python looks for a method in a hierarchy of classes. Especially it plays vital role in the context of multiple inheritance as single method may be found in multiple super classes. In the multiple inheritance scenario, any specified attribute is searched first in the current class. If not found, the search continues into parent classes in depth-first, left-right fashion without searching same class twice and then finally in object class. As every class in Python is derived from the class object. So, In above example , MRO will be GermanShephard, Dog, GoodAnimals, Object Dog GoodAnimals GermanShepar d
  • 16.
    MRO OF ACLASS(In case of Multiple Inheritance): class GoodAnimals(object): def __init__(self): print("They're all good dogs") super().__init__() class GermanShepard(Dog,GoodAnimals): def __init__(self): print("init GermanShepard") super().__init__() # calling base class constructor obj = GermanShepard() print(GermanShephard.__mro__) print(GermanShephard.mro()) MRO of a class can be viewed by using __mro__ attribute or mro() method. Create class Dog,GoodAnimals , GermanShephard inherits Dog and Goodanimals. Then display MRO of GermanShephard class Dog: def __init__(self): print("init Dog") super().__init__()
  • 17.
    MRO IN CASEOF MULTIPLE INHERITANCE class GoodAnimals(object): def __init__(self): print("They're all good dogs") super().__init__() class Dog: def __init__(self): print("init Dog") super().__init__() #pass the call to #next class in #MRO class GermanShepard(Dog,GoodAnimals): def __init__(self): print("init GermanShepard") super().__init__() # calling base class constructor obj = GermanShepard() Output • When the GermanShepard object is created, MRO searches for __init__() firstly in GermanShepard itself. • GermanShepard init is calling super init() will call init of next class in MRO i.e. Dog class init • Dog class init is calling super init() again which will call init of next class in MRO i.e. GoodAnimals class init In multiple inheritance, if you want constructor of child should call constructor of all parent classes. Then all parent and Child classes should call super().__init__()