SlideShare a Scribd company logo
Inheritance And
Polymorphism
Team Emertxe
Significance of Inheritance
Significance Of Inheritance
Example-1: teacher.py
# A Python program to create Teacher class and store it into teacher.py module.
# This is Teacher class. save this code in teaccher.py file
class Teacher:
def setid(self, id):
self.id = id
def getid(self):
return self.id
def setname(self, name):
self.name = name
def getname(self):
return self.name
def setaddress(self, address):
self.address = address
def getaddress(self):
return self.address
def setsalary(self, salary):
self.salary = salary
def getsalary(self):
return self.salary
When the programmer wants to use this Teacher class that is available in teachers.py file,
he can simply import this class into his program and use it
Significance Of Inheritance
Program
# using Teacher class from teacher important Teacher
from teacher import Teacher
# create instance
t = Teacher()
# store data into the instance
t.setid(10)
t.setname("Ram")
t.setaddress('HNO-10, Raj gardens, Delhi')
t.setsalary(25000.50)
# retrive data from instance and display
print('id= ', t.getid())
print('name= ', t.getname())
print('address= ', t.getaddress())
print('salary= ', t.getsalary())
Significance Of Inheritance
teacher.py
programmer1
programmer2
Significance Of Inheritance
Example-2: student.py
# A Python program to create sudent class and store it into student.py module
class Student:
def setid(self, id):
self.id = id
def getid(self):
return self.id
def setname(self, name):
self.name = name
def getname(self):
return self.name
def setaddress(self, address):
self.address = address
def getaddress(self):
return self.address
def setmarks(self, marks):
self.marks = marks
def getmarks(self):
return self.marks
Now, the second programmer who created this Student class and saved it as student.py
can use it whenever he needs.
Significance Of Inheritance
Program
# using student class from student import student
from student import Student
# create instance
s = Student()
# store data into the instance
s.setid(100)
s.setname('Rakesh')
s.setaddress('HNO-22, Ameerpet, Hyderabad')
s.setmarks(970)
#Print the data
print("ID: ", s.getid())
print("Name: ", s.getname())
print("Address: ", s.getaddress())
print("Marks: ", s.getmarks())
Significance Of Inheritance
Comparision
class Teacher:
def setid(self, id):
self.id = id
def getid(self):
return self.id
def setname(self, name):
self.name = name
def getname(self):
return self.name
def setaddress(self, address):
self.address = address
def getaddress(self):
return self.address
def setsalary(self, salary):
self.salary = salary
def getsalary(self):
return self.salary
class Student:
def setid(self, id):
self.id = id
def getid(self):
return self.id
def setname(self, name):
self.name = name
def getname(self):
return self.name
def setaddress(self, address):
self.address = address
def getaddress(self):
return self.address
def setmarks(self, marks):
self.marks = marks
def getmarks(self):
return self.marks
By comparing both the codes, we can observe 75% of the code is common
Significance Of Inheritance
from teacher import Teacher
class Student(Teacher):
def setmarks(self, marks):
self.marks = marks
def getmarks(self):
return self.marks
# create instance
s = Student()
# store data into the instance
s.setid(100)
s.setname('Rakesh')
s.setaddress('HNO-22, Ameerpet, Hyderabad')
s.setmarks(970)
#Print the data
print("ID: ", s.getid())
print("Name: ", s.getname())
print("Address: ", s.getaddress())
print("Marks: ", s.getmarks())
Syntax:
class Subclass(Baseclass):
Significance Of Inheritance
Advantages

Smaller and easier to develop

Productivity increases
marks
setmarks(), getmarks()
id
name
address
salary
setid(), getid()
setname(), getname()
setaddress(), getaddress()
setsalary(), getsalary()
Student class Object
Copy of Teacher class object
s
Inheritance
Definition

Deriving the new classes from the existing classes such that the new classes inherit all
the members of the existing classes is called Inheritance

Syntax:
class Subclass(Baseclass):
Constructors in Inheritance
Constructors in Inheritance
Example

Like variables & Methods, the constructors in the super class are also available in the
sub-class
class Father:
def __init__(self):
self.property = 800000.00
def display_property(self):
print('Father's property= ',self.property)
#Create the instance
s = Son()
s.display_property()
class Son(Father):
pass # we do not want to write anything in the sub class
Overriding Super Class
Constructors and Methods
Overriding super class
Constructors + Methods

Constructor Overriding
- The sub-class constructor is replacing the super class constructor

Method Overriding
- The sub-class method is replacing the super class method
Example
# overriding the base class constructor and method in sub class
class Father:
def __init__(self):
self.property = 800000.00
def display_property(self):
print('Father's property= ', self.property)
class Son(Father):
def __init__(self):
self.property = 200000.00
def display_property(self):
print('child's property= ', self.property)
# create sub class instance and display father's property
s = Son()
s.display_property()
The Super() Method
The super() Method

super() is a built-in method which is useful to call the super class constructor or Methods
Examples
#Call super class constructors
super().__init__()
#Call super class constructors and pass arguments
super().__init__(arguments)
#Call super class method
super().method()
The super() Method
Example
Example-1
# acceessing base class constructor in sub class
class Father:
def __init__(self, property=0):
self.property = property
def display_property(self):
print('Father's property= ', self.property)
class Son(Father):
def __init__(self, property1=0, property=0):
super().__init__(property)
self.property1 = property1
def display_property(self):
print('Total property of child= ', self.property1 + self.property)
# create sub class instance and display father's property
s = Son(200000.00, 800000.00)
s.display_property()
The super() Method
Example
Example-2
# Accessing base class constructor and method in the sub class
class Square:
def __init__(self, x):
self.x = x
def area(self):
print('Area of square= ',self.x * self.x)
class Rectangle(Square):
def __init__(self, x, y):
super().__init__(x)
self.y = y
def area(self):
super().area()
print('Area of rectangle= ',self.x * self.y)
# find areas of square and rectangle
a, b = [float(x) for x in input("Enter two measurements: ").split()]
r = Rectangle(a,b)
r.area()
Types Of Inheritance
Types of Inheritance
Single
Bank
AndhraBank StateBank
# A Python program showing single inhertiance in which two sub classes are derived from a
single base class.
# single inhertiance
class Bank(object):
cash = 100000000
@classmethod
def available_cash(cls):
print(cls.cash)
class StateBank(Bank):
cash = 200000000
@classmethod
def available_cash(cls):
print(cls.cash + Bank.cash)
class AndhraBank(Bank):
pass
a = AndhraBank()
a.available_cash()
s = StateBank()
s.available_cash()
Types of Inheritance
Multiple
Father Mother
# A Python program to implement multiple inhertiance using two base classes
#multiple inheritance
class Father:
def height(self):
print('Height is 6.0 foot')
class child(Father, Mother):
pass
class Mother:
def color(self):
print('color is brown')
c = child()
print('child's inherited qualities: ')
c.height()
c.color()
Child
Syntax:
class Subclass(BaseClass1, BaseClass2, ...):
Multiple Inheritance
Problems in MI
# A Python program to prove that only one class constructor is available to sub class in
multiple inheritance.
# when super classes have constructors
class A(object):
def __init__(self):
self.a = 'a'
print(self.a)
class B(object):
def __init__(self):
self.b = 'b'
print(self.b)
class C(A, B):
def __init__(self):
self.c = 'c'
print(self.c)
super().__init__()
# access the super class instance vars from C
o = C() # o is object of class C
Multiple Inheritance
Solutions
#A Python program to access all the instance variables of both the base classes in
multiple inheritance.
# when super classes have constructors - v2.0
class A(object):
def __init__(self):
self.a = 'a'
print(self.a)
super().__init__()
class B(object):
def __init__(self):
self.b = 'b'
print(self.b)
super().__init__()
class C(A,B):
def __init__(self):
self.c = 'c'
print(self.c)
super().__init__()
# access the super class instance vars from C
o = C() # o is object class C
Object
A B
C
MRO(Method Resolution Operator)
MRO

In Multiple Inheritance, any specified attribute or method is searched first in the current
class. If not found, the search continues into parent classes in depth-first left to right
fasion without searching for the same class twice
1. The first principle is to search for the sub classes before going for its base classes.
Thus if class B is inherited from A, it will search B first and then goes to A
2. The second principle is that when a class is inherited from several classes, it searches
in the order from left to right in the base class.
Example: class C(A, B), then first it will search in A and then in B
3. The third principle is that it will not visit any class more than once. That means a class
in the inheritance hierarchy is traversed only once exactly
MRO
Object
A B C
X Y
P
MRO
Program
# A Python program to understand the order of execution of methods in several base classes
according to MRO.
class A(object):
def method(self):
print('A class method')
super().method()
class B(object):
def method(self):
print('B class method')
super().method()
class C(object):
def method(self):
print('C class method')
class X(A, B):
def method(self):
print('X class method')
super().method()
class Y(A, B):
def method(self):
print('Y class method')
super().method()
class P(X,Y,C):
def method(self):
print('P class method')
super().method()
P = P()
P.method()
P.mro(): Returns sequence of execution of classes
Polymorphism
Polymorphism
Polymorphism
Introduction

Variable, Object or Method exhibits different behavior in different contexts called

Polymorphism

Python has built-in Polymorphism
Polymorphism
Duck Typing Philosophy

Datatype of the variables is not explicitly declared

type(): To check the type of variable or object
Example-1
x = 5
print(type(x))
<class ‘int’>
Example-2 x = “Hello”
print(type(x))
<class ‘str’>
Conclusion
1. Python’s type system is strong because every variable or object has a type that we can
check with the type() function
2. Python’s type system is ‘dynamic’ since the type of a variable is not explicitly declared,
but it changes with the content being stored
Polymorphism
Duck Typing Philosophy: Program
# A Python program to invoke a method on an object without knowing the type (or class) of
the object.
# duck typing example
# Duck class contains talk() method
class Duck:
def talk(self):
print('Quack, quack!')
#Human class contains talk() method
class Human:
def talk(self):
print('Hello, hi!')
# this method accepts an object and calls talk() method
def call_talk(obj):
obj.talk()
# call call_talk() method pass an object
# depending on type of object, talk() method is executed
x = Duck()
call_talk(x)
x = Human()
call_talk(x)
During runtime, if it is found that method does not belong to that object,
there will be an error called ‘AttributeError’
Polymorphism
Attribute Error: Overcoming
# this method accepts an object and calls talk() method
def call_talk(obj):
if hasattr(obj, 'talk'):
obj.talk()
elif hasattr(obj, 'bark'):
obj.bark()
else:
print('Wrong object passed...')
During runtime, if it is found that method does not belong to that object,
there will be an error called ‘AttributeError’
Operator Overloading
Operator Overloading
Example-1
# A Python program to use addition operator to act on different types of objects.
# overloading the + operator
# using + on integers to add them
print(10+15)
#using + on strings to concatenate them
s1 = "Red"
s2 = "Fort"
print(s1+s2)
#using + on lists to make a single list
a = [10, 20, 30]
b = [5, 15, -10]
print(a+b)
‘+’ operator is overloaded and thus exhibits polymorphism
Operator Overloading
Example-2
# Error #Correction
# using + operator on objects
class BookX:
def __init__(self, pages):
self.pages = pages
class BookY:
def __init__(self, pages):
self.pages = pages
b1 = BookX(100)
b2 = BookY(150)
print('Total pages = ', b1 + b2)
# overloading + operator to act on objects
class BookX:
def __init__(self, pages):
self.pages = pages
def __add__(self, other):
return self.pages+other.pages
class BookY:
def __init__(self, pages):
self.pages = pages
b1 = BookX(100)
b2 = BookY(150)
print('Total pages= ', b1+b2)
def __add__(self, other):
Operator Overloading
Example-3
#A Python program to overload greater than (>) operator to make it act on class objects.
# overloading > operator
class Ramayan:
def __init__(self, pages):
self.pages = pages
def __gt__(self, other):
return self.pages > other.pages
class Mahabharat:
def __init__(self, pages):
self.pages = pages
b1 = Ramayan(1000)
b2 = Mahabharat(1500)
if(b1 > b2):
print('Ramayan has more pages')
else:
print('Mahabharat has more pages')
def __gt__(self, other):
Method Overloading
Operator Overloading
Example-1
# A Python program to show method overloading to find sum of two or three numbers.
# method overloading
class Myclass:
def sum(self, a=None, b=None, c=None):
if a!=None and b!=None and c!=None:
print('Sum of three= ', a + b + c)
elif a!=None and b!=None:
print('Sum of two= ', a + b)
else:
print('Please enter two or three arguments')
# call sum() using object
m = Myclass()
m.sum(10, 15, 20)
m.sum(10.5, 25.55)
m.sum(100)
If a method is written such that it can perform more than one task, it is
called method overloading
Method Overriding
Operator Overriding
Example-1
# A Python program to override the super class method in sub class.
# method overriding
import math
class Square:
def area(self, x):
print('Square area= %.4f' % (x * x))
class Circle(Square):
def area(self, x):
print('Circle area= %.4f' % (math.pi *x * x))
# call area() using sub class object
c = Circle()
c.area(15)
If a method written in sub class overrides the same method in super class,
then it is called method overriding
Method overriding already discussed in Constructor & Method Overridings
THANK YOU

More Related Content

What's hot (20)

Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Polymorphism in Python
Polymorphism in Python Polymorphism in Python
Polymorphism in Python
Home
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
Binay Kumar Ray
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
Kamal Acharya
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
OOP concepts -in-Python programming language
OOP concepts -in-Python programming languageOOP concepts -in-Python programming language
OOP concepts -in-Python programming language
SmritiSharma901052
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
Srinivas Narasegouda
 
Modules in Python Programming
Modules in Python ProgrammingModules in Python Programming
Modules in Python Programming
sambitmandal
 
Python-Classes.pptx
Python-Classes.pptxPython-Classes.pptx
Python-Classes.pptx
Karudaiyar Ganapathy
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
Sujith Kumar
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
Praveen M Jigajinni
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
Vinod Kumar
 
Python-Encapsulation.pptx
Python-Encapsulation.pptxPython-Encapsulation.pptx
Python-Encapsulation.pptx
Karudaiyar Ganapathy
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Polymorphism in Python
Polymorphism in Python Polymorphism in Python
Polymorphism in Python
Home
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
OOP concepts -in-Python programming language
OOP concepts -in-Python programming languageOOP concepts -in-Python programming language
OOP concepts -in-Python programming language
SmritiSharma901052
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
Srinivas Narasegouda
 
Modules in Python Programming
Modules in Python ProgrammingModules in Python Programming
Modules in Python Programming
sambitmandal
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
Sujith Kumar
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
rajshreemuthiah
 

Similar to Python programming : Inheritance and polymorphism (20)

All about python Inheritance.python codingdf
All about python Inheritance.python codingdfAll about python Inheritance.python codingdf
All about python Inheritance.python codingdf
adipapai181023
 
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
InheritanceInheritance
Inheritance
JayanthiNeelampalli
 
Inheritance Super and MRO _
Inheritance Super and MRO               _Inheritance Super and MRO               _
Inheritance Super and MRO _
swati463221
 
Inheritance_in_OOP_using Python Programming
Inheritance_in_OOP_using Python ProgrammingInheritance_in_OOP_using Python Programming
Inheritance_in_OOP_using Python Programming
abigailjudith8
 
Object oriented Programning Lanuagues in text format.
Object oriented Programning Lanuagues in text format.Object oriented Programning Lanuagues in text format.
Object oriented Programning Lanuagues in text format.
SravaniSravani53
 
Inheritance and polymorphism oops concepts in python
Inheritance and polymorphism  oops concepts in pythonInheritance and polymorphism  oops concepts in python
Inheritance and polymorphism oops concepts in python
deepalishinkar1
 
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
 
601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx
srinivasa gowda
 
arthimetic operator,classes,objects,instant
arthimetic operator,classes,objects,instantarthimetic operator,classes,objects,instant
arthimetic operator,classes,objects,instant
ssuser77162c
 
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
 
Lecture on Python OP concepts of Polymorpysim and Inheritance.pdf
Lecture on Python OP concepts of Polymorpysim and Inheritance.pdfLecture on Python OP concepts of Polymorpysim and Inheritance.pdf
Lecture on Python OP concepts of Polymorpysim and Inheritance.pdf
waqaskhan428678
 
object oriented programming(PYTHON)
object oriented programming(PYTHON)object oriented programming(PYTHON)
object oriented programming(PYTHON)
Jyoti shukla
 
Python advance
Python advancePython advance
Python advance
Mukul Kirti Verma
 
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
 
Python Programming - VIII. Inheritance and Polymorphism
Python Programming - VIII. Inheritance and PolymorphismPython Programming - VIII. Inheritance and Polymorphism
Python Programming - VIII. Inheritance and Polymorphism
Ranel Padon
 
Class and Objects in python programming.pptx
Class and Objects in python programming.pptxClass and Objects in python programming.pptx
Class and Objects in python programming.pptx
Rajtherock
 
Presentation_4516_Content_Document_20250204010703PM.pptx
Presentation_4516_Content_Document_20250204010703PM.pptxPresentation_4516_Content_Document_20250204010703PM.pptx
Presentation_4516_Content_Document_20250204010703PM.pptx
MuhammadChala
 
oops-in-python-240412044200-2d5c6552.pptx
oops-in-python-240412044200-2d5c6552.pptxoops-in-python-240412044200-2d5c6552.pptx
oops-in-python-240412044200-2d5c6552.pptx
anilvarsha1
 
All about python Inheritance.python codingdf
All about python Inheritance.python codingdfAll about python Inheritance.python codingdf
All about python Inheritance.python codingdf
adipapai181023
 
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 Super and MRO _
Inheritance Super and MRO               _Inheritance Super and MRO               _
Inheritance Super and MRO _
swati463221
 
Inheritance_in_OOP_using Python Programming
Inheritance_in_OOP_using Python ProgrammingInheritance_in_OOP_using Python Programming
Inheritance_in_OOP_using Python Programming
abigailjudith8
 
Object oriented Programning Lanuagues in text format.
Object oriented Programning Lanuagues in text format.Object oriented Programning Lanuagues in text format.
Object oriented Programning Lanuagues in text format.
SravaniSravani53
 
Inheritance and polymorphism oops concepts in python
Inheritance and polymorphism  oops concepts in pythonInheritance and polymorphism  oops concepts in python
Inheritance and polymorphism oops concepts in python
deepalishinkar1
 
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
 
601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx601109769-Pythondyttcjycvuv-Inheritance .pptx
601109769-Pythondyttcjycvuv-Inheritance .pptx
srinivasa gowda
 
arthimetic operator,classes,objects,instant
arthimetic operator,classes,objects,instantarthimetic operator,classes,objects,instant
arthimetic operator,classes,objects,instant
ssuser77162c
 
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
 
Lecture on Python OP concepts of Polymorpysim and Inheritance.pdf
Lecture on Python OP concepts of Polymorpysim and Inheritance.pdfLecture on Python OP concepts of Polymorpysim and Inheritance.pdf
Lecture on Python OP concepts of Polymorpysim and Inheritance.pdf
waqaskhan428678
 
object oriented programming(PYTHON)
object oriented programming(PYTHON)object oriented programming(PYTHON)
object oriented programming(PYTHON)
Jyoti shukla
 
Python Programming - VIII. Inheritance and Polymorphism
Python Programming - VIII. Inheritance and PolymorphismPython Programming - VIII. Inheritance and Polymorphism
Python Programming - VIII. Inheritance and Polymorphism
Ranel Padon
 
Class and Objects in python programming.pptx
Class and Objects in python programming.pptxClass and Objects in python programming.pptx
Class and Objects in python programming.pptx
Rajtherock
 
Presentation_4516_Content_Document_20250204010703PM.pptx
Presentation_4516_Content_Document_20250204010703PM.pptxPresentation_4516_Content_Document_20250204010703PM.pptx
Presentation_4516_Content_Document_20250204010703PM.pptx
MuhammadChala
 
oops-in-python-240412044200-2d5c6552.pptx
oops-in-python-240412044200-2d5c6552.pptxoops-in-python-240412044200-2d5c6552.pptx
oops-in-python-240412044200-2d5c6552.pptx
anilvarsha1
 
Ad

More from Emertxe Information Technologies Pvt Ltd (20)

Career Transition (1).pdf
Career Transition (1).pdfCareer Transition (1).pdf
Career Transition (1).pdf
Emertxe Information Technologies Pvt Ltd
 
10_isxdigit.pdf
10_isxdigit.pdf10_isxdigit.pdf
10_isxdigit.pdf
Emertxe Information Technologies Pvt Ltd
 
01_student_record.pdf
01_student_record.pdf01_student_record.pdf
01_student_record.pdf
Emertxe Information Technologies Pvt Ltd
 
02_swap.pdf
02_swap.pdf02_swap.pdf
02_swap.pdf
Emertxe Information Technologies Pvt Ltd
 
01_sizeof.pdf
01_sizeof.pdf01_sizeof.pdf
01_sizeof.pdf
Emertxe Information Technologies Pvt Ltd
 
07_product_matrix.pdf
07_product_matrix.pdf07_product_matrix.pdf
07_product_matrix.pdf
Emertxe Information Technologies Pvt Ltd
 
06_sort_names.pdf
06_sort_names.pdf06_sort_names.pdf
06_sort_names.pdf
Emertxe Information Technologies Pvt Ltd
 
05_fragments.pdf
05_fragments.pdf05_fragments.pdf
05_fragments.pdf
Emertxe Information Technologies Pvt Ltd
 
04_magic_square.pdf
04_magic_square.pdf04_magic_square.pdf
04_magic_square.pdf
Emertxe Information Technologies Pvt Ltd
 
03_endianess.pdf
03_endianess.pdf03_endianess.pdf
03_endianess.pdf
Emertxe Information Technologies Pvt Ltd
 
02_variance.pdf
02_variance.pdf02_variance.pdf
02_variance.pdf
Emertxe Information Technologies Pvt Ltd
 
01_memory_manager.pdf
01_memory_manager.pdf01_memory_manager.pdf
01_memory_manager.pdf
Emertxe Information Technologies Pvt Ltd
 
09_nrps.pdf
09_nrps.pdf09_nrps.pdf
09_nrps.pdf
Emertxe Information Technologies Pvt Ltd
 
11_pangram.pdf
11_pangram.pdf11_pangram.pdf
11_pangram.pdf
Emertxe Information Technologies Pvt Ltd
 
10_combinations.pdf
10_combinations.pdf10_combinations.pdf
10_combinations.pdf
Emertxe Information Technologies Pvt Ltd
 
08_squeeze.pdf
08_squeeze.pdf08_squeeze.pdf
08_squeeze.pdf
Emertxe Information Technologies Pvt Ltd
 
07_strtok.pdf
07_strtok.pdf07_strtok.pdf
07_strtok.pdf
Emertxe Information Technologies Pvt Ltd
 
06_reverserec.pdf
06_reverserec.pdf06_reverserec.pdf
06_reverserec.pdf
Emertxe Information Technologies Pvt Ltd
 
05_reverseiter.pdf
05_reverseiter.pdf05_reverseiter.pdf
05_reverseiter.pdf
Emertxe Information Technologies Pvt Ltd
 
Ad

Recently uploaded (20)

7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
Edge AI and Vision Alliance
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Soulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate reviewSoulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate review
Soulmaite
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
ELNL2025 - Unlocking the Power of Sensitivity Labels - A Comprehensive Guide....
Jasper Oosterveld
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
“How Qualcomm Is Powering AI-driven Multimedia at the Edge,” a Presentation f...
Edge AI and Vision Alliance
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Soulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate reviewSoulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate review
Soulmaite
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 

Python programming : Inheritance and polymorphism

  • 3. Significance Of Inheritance Example-1: teacher.py # A Python program to create Teacher class and store it into teacher.py module. # This is Teacher class. save this code in teaccher.py file class Teacher: def setid(self, id): self.id = id def getid(self): return self.id def setname(self, name): self.name = name def getname(self): return self.name def setaddress(self, address): self.address = address def getaddress(self): return self.address def setsalary(self, salary): self.salary = salary def getsalary(self): return self.salary When the programmer wants to use this Teacher class that is available in teachers.py file, he can simply import this class into his program and use it
  • 4. Significance Of Inheritance Program # using Teacher class from teacher important Teacher from teacher import Teacher # create instance t = Teacher() # store data into the instance t.setid(10) t.setname("Ram") t.setaddress('HNO-10, Raj gardens, Delhi') t.setsalary(25000.50) # retrive data from instance and display print('id= ', t.getid()) print('name= ', t.getname()) print('address= ', t.getaddress()) print('salary= ', t.getsalary())
  • 6. Significance Of Inheritance Example-2: student.py # A Python program to create sudent class and store it into student.py module class Student: def setid(self, id): self.id = id def getid(self): return self.id def setname(self, name): self.name = name def getname(self): return self.name def setaddress(self, address): self.address = address def getaddress(self): return self.address def setmarks(self, marks): self.marks = marks def getmarks(self): return self.marks Now, the second programmer who created this Student class and saved it as student.py can use it whenever he needs.
  • 7. Significance Of Inheritance Program # using student class from student import student from student import Student # create instance s = Student() # store data into the instance s.setid(100) s.setname('Rakesh') s.setaddress('HNO-22, Ameerpet, Hyderabad') s.setmarks(970) #Print the data print("ID: ", s.getid()) print("Name: ", s.getname()) print("Address: ", s.getaddress()) print("Marks: ", s.getmarks())
  • 8. Significance Of Inheritance Comparision class Teacher: def setid(self, id): self.id = id def getid(self): return self.id def setname(self, name): self.name = name def getname(self): return self.name def setaddress(self, address): self.address = address def getaddress(self): return self.address def setsalary(self, salary): self.salary = salary def getsalary(self): return self.salary class Student: def setid(self, id): self.id = id def getid(self): return self.id def setname(self, name): self.name = name def getname(self): return self.name def setaddress(self, address): self.address = address def getaddress(self): return self.address def setmarks(self, marks): self.marks = marks def getmarks(self): return self.marks By comparing both the codes, we can observe 75% of the code is common
  • 9. Significance Of Inheritance from teacher import Teacher class Student(Teacher): def setmarks(self, marks): self.marks = marks def getmarks(self): return self.marks # create instance s = Student() # store data into the instance s.setid(100) s.setname('Rakesh') s.setaddress('HNO-22, Ameerpet, Hyderabad') s.setmarks(970) #Print the data print("ID: ", s.getid()) print("Name: ", s.getname()) print("Address: ", s.getaddress()) print("Marks: ", s.getmarks()) Syntax: class Subclass(Baseclass):
  • 10. Significance Of Inheritance Advantages  Smaller and easier to develop  Productivity increases marks setmarks(), getmarks() id name address salary setid(), getid() setname(), getname() setaddress(), getaddress() setsalary(), getsalary() Student class Object Copy of Teacher class object s
  • 11. Inheritance Definition  Deriving the new classes from the existing classes such that the new classes inherit all the members of the existing classes is called Inheritance  Syntax: class Subclass(Baseclass):
  • 13. Constructors in Inheritance Example  Like variables & Methods, the constructors in the super class are also available in the sub-class class Father: def __init__(self): self.property = 800000.00 def display_property(self): print('Father's property= ',self.property) #Create the instance s = Son() s.display_property() class Son(Father): pass # we do not want to write anything in the sub class
  • 15. Overriding super class Constructors + Methods  Constructor Overriding - The sub-class constructor is replacing the super class constructor  Method Overriding - The sub-class method is replacing the super class method Example # overriding the base class constructor and method in sub class class Father: def __init__(self): self.property = 800000.00 def display_property(self): print('Father's property= ', self.property) class Son(Father): def __init__(self): self.property = 200000.00 def display_property(self): print('child's property= ', self.property) # create sub class instance and display father's property s = Son() s.display_property()
  • 17. The super() Method  super() is a built-in method which is useful to call the super class constructor or Methods Examples #Call super class constructors super().__init__() #Call super class constructors and pass arguments super().__init__(arguments) #Call super class method super().method()
  • 18. The super() Method Example Example-1 # acceessing base class constructor in sub class class Father: def __init__(self, property=0): self.property = property def display_property(self): print('Father's property= ', self.property) class Son(Father): def __init__(self, property1=0, property=0): super().__init__(property) self.property1 = property1 def display_property(self): print('Total property of child= ', self.property1 + self.property) # create sub class instance and display father's property s = Son(200000.00, 800000.00) s.display_property()
  • 19. The super() Method Example Example-2 # Accessing base class constructor and method in the sub class class Square: def __init__(self, x): self.x = x def area(self): print('Area of square= ',self.x * self.x) class Rectangle(Square): def __init__(self, x, y): super().__init__(x) self.y = y def area(self): super().area() print('Area of rectangle= ',self.x * self.y) # find areas of square and rectangle a, b = [float(x) for x in input("Enter two measurements: ").split()] r = Rectangle(a,b) r.area()
  • 21. Types of Inheritance Single Bank AndhraBank StateBank # A Python program showing single inhertiance in which two sub classes are derived from a single base class. # single inhertiance class Bank(object): cash = 100000000 @classmethod def available_cash(cls): print(cls.cash) class StateBank(Bank): cash = 200000000 @classmethod def available_cash(cls): print(cls.cash + Bank.cash) class AndhraBank(Bank): pass a = AndhraBank() a.available_cash() s = StateBank() s.available_cash()
  • 22. Types of Inheritance Multiple Father Mother # A Python program to implement multiple inhertiance using two base classes #multiple inheritance class Father: def height(self): print('Height is 6.0 foot') class child(Father, Mother): pass class Mother: def color(self): print('color is brown') c = child() print('child's inherited qualities: ') c.height() c.color() Child Syntax: class Subclass(BaseClass1, BaseClass2, ...):
  • 23. Multiple Inheritance Problems in MI # A Python program to prove that only one class constructor is available to sub class in multiple inheritance. # when super classes have constructors class A(object): def __init__(self): self.a = 'a' print(self.a) class B(object): def __init__(self): self.b = 'b' print(self.b) class C(A, B): def __init__(self): self.c = 'c' print(self.c) super().__init__() # access the super class instance vars from C o = C() # o is object of class C
  • 24. Multiple Inheritance Solutions #A Python program to access all the instance variables of both the base classes in multiple inheritance. # when super classes have constructors - v2.0 class A(object): def __init__(self): self.a = 'a' print(self.a) super().__init__() class B(object): def __init__(self): self.b = 'b' print(self.b) super().__init__() class C(A,B): def __init__(self): self.c = 'c' print(self.c) super().__init__() # access the super class instance vars from C o = C() # o is object class C Object A B C
  • 26. MRO  In Multiple Inheritance, any specified attribute or method is searched first in the current class. If not found, the search continues into parent classes in depth-first left to right fasion without searching for the same class twice 1. The first principle is to search for the sub classes before going for its base classes. Thus if class B is inherited from A, it will search B first and then goes to A 2. The second principle is that when a class is inherited from several classes, it searches in the order from left to right in the base class. Example: class C(A, B), then first it will search in A and then in B 3. The third principle is that it will not visit any class more than once. That means a class in the inheritance hierarchy is traversed only once exactly
  • 28. MRO Program # A Python program to understand the order of execution of methods in several base classes according to MRO. class A(object): def method(self): print('A class method') super().method() class B(object): def method(self): print('B class method') super().method() class C(object): def method(self): print('C class method') class X(A, B): def method(self): print('X class method') super().method() class Y(A, B): def method(self): print('Y class method') super().method() class P(X,Y,C): def method(self): print('P class method') super().method() P = P() P.method() P.mro(): Returns sequence of execution of classes
  • 31. Polymorphism Introduction  Variable, Object or Method exhibits different behavior in different contexts called  Polymorphism  Python has built-in Polymorphism
  • 32. Polymorphism Duck Typing Philosophy  Datatype of the variables is not explicitly declared  type(): To check the type of variable or object Example-1 x = 5 print(type(x)) <class ‘int’> Example-2 x = “Hello” print(type(x)) <class ‘str’> Conclusion 1. Python’s type system is strong because every variable or object has a type that we can check with the type() function 2. Python’s type system is ‘dynamic’ since the type of a variable is not explicitly declared, but it changes with the content being stored
  • 33. Polymorphism Duck Typing Philosophy: Program # A Python program to invoke a method on an object without knowing the type (or class) of the object. # duck typing example # Duck class contains talk() method class Duck: def talk(self): print('Quack, quack!') #Human class contains talk() method class Human: def talk(self): print('Hello, hi!') # this method accepts an object and calls talk() method def call_talk(obj): obj.talk() # call call_talk() method pass an object # depending on type of object, talk() method is executed x = Duck() call_talk(x) x = Human() call_talk(x) During runtime, if it is found that method does not belong to that object, there will be an error called ‘AttributeError’
  • 34. Polymorphism Attribute Error: Overcoming # this method accepts an object and calls talk() method def call_talk(obj): if hasattr(obj, 'talk'): obj.talk() elif hasattr(obj, 'bark'): obj.bark() else: print('Wrong object passed...') During runtime, if it is found that method does not belong to that object, there will be an error called ‘AttributeError’
  • 36. Operator Overloading Example-1 # A Python program to use addition operator to act on different types of objects. # overloading the + operator # using + on integers to add them print(10+15) #using + on strings to concatenate them s1 = "Red" s2 = "Fort" print(s1+s2) #using + on lists to make a single list a = [10, 20, 30] b = [5, 15, -10] print(a+b) ‘+’ operator is overloaded and thus exhibits polymorphism
  • 37. Operator Overloading Example-2 # Error #Correction # using + operator on objects class BookX: def __init__(self, pages): self.pages = pages class BookY: def __init__(self, pages): self.pages = pages b1 = BookX(100) b2 = BookY(150) print('Total pages = ', b1 + b2) # overloading + operator to act on objects class BookX: def __init__(self, pages): self.pages = pages def __add__(self, other): return self.pages+other.pages class BookY: def __init__(self, pages): self.pages = pages b1 = BookX(100) b2 = BookY(150) print('Total pages= ', b1+b2) def __add__(self, other):
  • 38. Operator Overloading Example-3 #A Python program to overload greater than (>) operator to make it act on class objects. # overloading > operator class Ramayan: def __init__(self, pages): self.pages = pages def __gt__(self, other): return self.pages > other.pages class Mahabharat: def __init__(self, pages): self.pages = pages b1 = Ramayan(1000) b2 = Mahabharat(1500) if(b1 > b2): print('Ramayan has more pages') else: print('Mahabharat has more pages') def __gt__(self, other):
  • 40. Operator Overloading Example-1 # A Python program to show method overloading to find sum of two or three numbers. # method overloading class Myclass: def sum(self, a=None, b=None, c=None): if a!=None and b!=None and c!=None: print('Sum of three= ', a + b + c) elif a!=None and b!=None: print('Sum of two= ', a + b) else: print('Please enter two or three arguments') # call sum() using object m = Myclass() m.sum(10, 15, 20) m.sum(10.5, 25.55) m.sum(100) If a method is written such that it can perform more than one task, it is called method overloading
  • 42. Operator Overriding Example-1 # A Python program to override the super class method in sub class. # method overriding import math class Square: def area(self, x): print('Square area= %.4f' % (x * x)) class Circle(Square): def area(self, x): print('Circle area= %.4f' % (math.pi *x * x)) # call area() using sub class object c = Circle() c.area(15) If a method written in sub class overrides the same method in super class, then it is called method overriding Method overriding already discussed in Constructor & Method Overridings