SlideShare a Scribd company logo
2
Most read
3
Most read
4
Most read
Polymorphism
Damian Gordon
Polymorphism
• Polymorphism simply means that we can call the same method
name with parameters, and depending on the parameters, it
will do different things. For example:
>>> print(6 * 5)
>>> print(“Hello” * 5)
Polymorphism
• Polymorphism simply means that we can call the same method
name with parameters, and depending on the parameters, it
will do different things. For example:
>>> print(6 * 5)
>>> print(“Hello” * 5)
Mult (6, 5)
Mult (“Hello”, 5)
Polymorphism
• Polymorphism simply means that we can call the same method
name with parameters, and depending on the parameters, it
will do different things. For example:
>>> print(6 * 5)
>>> print(“Hello” * 5)
Mult (6, 5)
Mult (“Hello”, 5)
30
HelloHelloHelloHelloHello
Polymorphism
• A more complicated example to consider would be to think
about creating a method called play() to play an audio file.
• A media player will be needed to load the AudioFile object.
• The instruction to play the file might be as simple as:
>>> audio_file.play( )
Polymorphism
• However, different audio files use different compression
algorithms (e.g. .mp3, .wma, .ogg), and some aren’t stored as
compressed at all (e.g. .wav).
• We can use inheritance with polymorphism to simplify the
design. Each filetype is represented as a different subclass of
AudioFile, and each of those has a play( ) method.
Polymorphism
AudioFile
_ _init_ _( )
MP3File
play( )
WAVFile
play( )
OGGFile
play( )
Polymorphism
class AudioFile:
def _ _init_ _(self, filename):
if not filename.endswith(self.ext):
# THEN
raise Exception(“Invalid format”)
# ENDIF;
self.filename = filename
# END init()
# END CLASS.
Polymorphism
class AudioFile:
def _ _init_ _(self, filename):
if not filename.endswith(self.ext):
# THEN
raise Exception(“Invalid format”)
# ENDIF;
self.filename = filename
# END init()
# END CLASS.
Check if the file extension
of the audio being played
is a known extension,
self.ext is set in each
of the subclasses.
Raise an exception if it’s an
unknown file extension
If it’s a known file
extension, then assign the
filename passed in to
self.filename
Polymorphism
class MP3File(AudioFile):
ext = “mp3”
def play(self):
print(“playing {} as mp3”.format(self.filename))
# END play
# END CLASS.
Polymorphism
class WAVFile(AudioFile):
ext = “wav”
def play(self):
print(“playing {} as wav”.format(self.filename))
# END play
# END CLASS.
Polymorphism
class OGGFile(AudioFile):
ext = “ogg”
def play(self):
print(“playing {} as ogg”.format(self.filename))
# END play
# END CLASS.
Polymorphism
• Here’s how we run it:
>>> mp3 = MP3File(“myfile.mp3”)
>>> mp3.play()
playing myfile.mp3 as mp3
Polymorphism
• Here’s another one:
>>> wav = WAVFile(“myfile.wav”)
>>> wav.play()
playing myfile.wav as wav
Polymorphism
• Here’s an error:
>>> ogg_declared_as_mp3 = MP3File("myfile.ogg")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "polymorphic_audio.py", line 4, in __init__
raise Exception("Invalid format")
Exception: Invalid format
etc.

More Related Content

What's hot (20)

ODP
Python Modules
Nitin Reddy Katkam
 
PPTX
Data types in python
RaginiJain21
 
PPTX
Basics of Object Oriented Programming in Python
Sujith Kumar
 
PDF
Datatypes in python
eShikshak
 
PDF
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
PDF
Operator overloading
Pranali Chaudhari
 
PDF
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
PPSX
Modules and packages in python
TMARAGATHAM
 
PPTX
Chapter 07 inheritance
Praveen M Jigajinni
 
PPT
Introduction to Python
Nowell Strite
 
PPTX
Method overloading
Lovely Professional University
 
PDF
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
PDF
Methods in Java
Jussi Pohjolainen
 
PPTX
Chapter 05 classes and objects
Praveen M Jigajinni
 
PPTX
Operators in Python
Anusuya123
 
PDF
Function overloading ppt
Prof. Dr. K. Adisesha
 
PPTX
String matching algorithms
Ashikapokiya12345
 
PPTX
Python Functions
Mohammed Sikander
 
PPTX
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
Python Modules
Nitin Reddy Katkam
 
Data types in python
RaginiJain21
 
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Datatypes in python
eShikshak
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Operator overloading
Pranali Chaudhari
 
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Modules and packages in python
TMARAGATHAM
 
Chapter 07 inheritance
Praveen M Jigajinni
 
Introduction to Python
Nowell Strite
 
Method overloading
Lovely Professional University
 
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
Methods in Java
Jussi Pohjolainen
 
Chapter 05 classes and objects
Praveen M Jigajinni
 
Operators in Python
Anusuya123
 
Function overloading ppt
Prof. Dr. K. Adisesha
 
String matching algorithms
Ashikapokiya12345
 
Python Functions
Mohammed Sikander
 
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 

Viewers also liked (13)

PPTX
Object-Orientated Design
Damian T. Gordon
 
PPTX
Introduction to Python programming
Damian T. Gordon
 
PPTX
Python: Multiple Inheritance
Damian T. Gordon
 
PPTX
Python: Third-Party Libraries
Damian T. Gordon
 
PPTX
Python: Access Control
Damian T. Gordon
 
PPTX
Python: The Iterator Pattern
Damian T. Gordon
 
PPTX
Python: Modules and Packages
Damian T. Gordon
 
PPTX
Python: Design Patterns
Damian T. Gordon
 
PPTX
Python: Basic Inheritance
Damian T. Gordon
 
PPTX
Creating Objects in Python
Damian T. Gordon
 
PPTX
Python: Manager Objects
Damian T. Gordon
 
PPTX
Python: Migrating from Procedural to Object-Oriented Programming
Damian T. Gordon
 
PPTX
The Extreme Programming (XP) Model
Damian T. Gordon
 
Object-Orientated Design
Damian T. Gordon
 
Introduction to Python programming
Damian T. Gordon
 
Python: Multiple Inheritance
Damian T. Gordon
 
Python: Third-Party Libraries
Damian T. Gordon
 
Python: Access Control
Damian T. Gordon
 
Python: The Iterator Pattern
Damian T. Gordon
 
Python: Modules and Packages
Damian T. Gordon
 
Python: Design Patterns
Damian T. Gordon
 
Python: Basic Inheritance
Damian T. Gordon
 
Creating Objects in Python
Damian T. Gordon
 
Python: Manager Objects
Damian T. Gordon
 
Python: Migrating from Procedural to Object-Oriented Programming
Damian T. Gordon
 
The Extreme Programming (XP) Model
Damian T. Gordon
 
Ad

Similar to Python: Polymorphism (20)

PDF
Master of computer application python programming unit 3.pdf
Krrai1
 
PPTX
Polymorphism.pptx
TuanMinhHuynh3
 
PPTX
Python programming computer science and engineering
IRAH34
 
PPTX
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
PPTX
Module 3,4.pptx
SandeepR95
 
PPT
Object Orientation vs. Functional Programming in Python
Python Ireland
 
PPTX
Polymorphism
CME
 
PPTX
polymorphismppt for Computer Applications-211218133624.pptx
waarrior1234567
 
PPTX
Polymorphism.pptx
Vijaykota11
 
PPTX
oogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptx
BhojarajTheking
 
PDF
Python file handling
Prof. Dr. K. Adisesha
 
PDF
Lecture on Lecture on Python programming OP conceptsPolymorphism.pdf
waqaskhan428678
 
PDF
Learn Polymorphism in Python with Examples.pdf
Datacademy.ai
 
PPTX
9-_Object_Oriented_Programming_Using_Python 1.pptx
Lahari42
 
PPTX
Intro to Python (High School) Unit #2
Jay Coskey
 
PDF
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
PPTX
Python-Polymorphism.pptx
Karudaiyar Ganapathy
 
PPTX
PYTHON OBJECT-ORIENTED PROGRAMMING.pptx
hpearl130
 
PPTX
Python files / directories part16
Vishal Dutt
 
PPTX
5-filehandling-2004054567151830 (1).pptx
lionsconvent1234
 
Master of computer application python programming unit 3.pdf
Krrai1
 
Polymorphism.pptx
TuanMinhHuynh3
 
Python programming computer science and engineering
IRAH34
 
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
Module 3,4.pptx
SandeepR95
 
Object Orientation vs. Functional Programming in Python
Python Ireland
 
Polymorphism
CME
 
polymorphismppt for Computer Applications-211218133624.pptx
waarrior1234567
 
Polymorphism.pptx
Vijaykota11
 
oogshsvshsbhshhshvsvshsvsvhshshjshshhsvgps.pptx
BhojarajTheking
 
Python file handling
Prof. Dr. K. Adisesha
 
Lecture on Lecture on Python programming OP conceptsPolymorphism.pdf
waqaskhan428678
 
Learn Polymorphism in Python with Examples.pdf
Datacademy.ai
 
9-_Object_Oriented_Programming_Using_Python 1.pptx
Lahari42
 
Intro to Python (High School) Unit #2
Jay Coskey
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
Python-Polymorphism.pptx
Karudaiyar Ganapathy
 
PYTHON OBJECT-ORIENTED PROGRAMMING.pptx
hpearl130
 
Python files / directories part16
Vishal Dutt
 
5-filehandling-2004054567151830 (1).pptx
lionsconvent1234
 
Ad

More from Damian T. Gordon (20)

PPTX
Introduction to Prompts and Prompt Engineering
Damian T. Gordon
 
PPTX
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
PPTX
TRIZ: Theory of Inventive Problem Solving
Damian T. Gordon
 
PPTX
Some Ethical Considerations of AI and GenAI
Damian T. Gordon
 
PPTX
Some Common Errors that Generative AI Produces
Damian T. Gordon
 
PPTX
The Use of Data and Datasets in Data Science
Damian T. Gordon
 
PPTX
A History of Different Versions of Microsoft Windows
Damian T. Gordon
 
PPTX
Writing an Abstract: A Question-based Approach
Damian T. Gordon
 
PPTX
Using GenAI for Universal Design for Learning
Damian T. Gordon
 
DOC
A CheckSheet for Inclusive Software Design
Damian T. Gordon
 
PPTX
A History of Versions of the Apple MacOS
Damian T. Gordon
 
PPTX
68 Ways that Data Science and AI can help address the UN Sustainability Goals
Damian T. Gordon
 
PPTX
Copyright and Creative Commons Considerations
Damian T. Gordon
 
PPTX
Exam Preparation: Some Ideas and Suggestions
Damian T. Gordon
 
PPTX
Studying and Notetaking: Some Suggestions
Damian T. Gordon
 
PPTX
The Growth Mindset: Explanations and Activities
Damian T. Gordon
 
PPTX
Hyperparameter Tuning in Neural Networks
Damian T. Gordon
 
PPTX
Early 20th Century Modern Art: Movements and Artists
Damian T. Gordon
 
PPTX
An Introduction to Generative Artificial Intelligence
Damian T. Gordon
 
PPTX
An Introduction to Green Computing with a fun quiz.
Damian T. Gordon
 
Introduction to Prompts and Prompt Engineering
Damian T. Gordon
 
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
TRIZ: Theory of Inventive Problem Solving
Damian T. Gordon
 
Some Ethical Considerations of AI and GenAI
Damian T. Gordon
 
Some Common Errors that Generative AI Produces
Damian T. Gordon
 
The Use of Data and Datasets in Data Science
Damian T. Gordon
 
A History of Different Versions of Microsoft Windows
Damian T. Gordon
 
Writing an Abstract: A Question-based Approach
Damian T. Gordon
 
Using GenAI for Universal Design for Learning
Damian T. Gordon
 
A CheckSheet for Inclusive Software Design
Damian T. Gordon
 
A History of Versions of the Apple MacOS
Damian T. Gordon
 
68 Ways that Data Science and AI can help address the UN Sustainability Goals
Damian T. Gordon
 
Copyright and Creative Commons Considerations
Damian T. Gordon
 
Exam Preparation: Some Ideas and Suggestions
Damian T. Gordon
 
Studying and Notetaking: Some Suggestions
Damian T. Gordon
 
The Growth Mindset: Explanations and Activities
Damian T. Gordon
 
Hyperparameter Tuning in Neural Networks
Damian T. Gordon
 
Early 20th Century Modern Art: Movements and Artists
Damian T. Gordon
 
An Introduction to Generative Artificial Intelligence
Damian T. Gordon
 
An Introduction to Green Computing with a fun quiz.
Damian T. Gordon
 

Recently uploaded (20)

PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PPTX
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
PDF
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
PDF
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PPTX
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PATIENT ASSIGNMENTS AND NURSING CARE RESPONSIBILITIES.pptx
PRADEEP ABOTHU
 
QNL June Edition hosted by Pragya the official Quiz Club of the University of...
Pragya - UEM Kolkata Quiz Club
 
ARAL-Orientation_Morning-Session_Day-11.pdf
JoelVilloso1
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
How to Convert an Opportunity into a Quotation in Odoo 18 CRM
Celine George
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Dimensions of Societal Planning in Commonism
StefanMz
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
community health nursing question paper 2.pdf
Prince kumar
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 

Python: Polymorphism

  • 2. Polymorphism • Polymorphism simply means that we can call the same method name with parameters, and depending on the parameters, it will do different things. For example: >>> print(6 * 5) >>> print(“Hello” * 5)
  • 3. Polymorphism • Polymorphism simply means that we can call the same method name with parameters, and depending on the parameters, it will do different things. For example: >>> print(6 * 5) >>> print(“Hello” * 5) Mult (6, 5) Mult (“Hello”, 5)
  • 4. Polymorphism • Polymorphism simply means that we can call the same method name with parameters, and depending on the parameters, it will do different things. For example: >>> print(6 * 5) >>> print(“Hello” * 5) Mult (6, 5) Mult (“Hello”, 5) 30 HelloHelloHelloHelloHello
  • 5. Polymorphism • A more complicated example to consider would be to think about creating a method called play() to play an audio file. • A media player will be needed to load the AudioFile object. • The instruction to play the file might be as simple as: >>> audio_file.play( )
  • 6. Polymorphism • However, different audio files use different compression algorithms (e.g. .mp3, .wma, .ogg), and some aren’t stored as compressed at all (e.g. .wav). • We can use inheritance with polymorphism to simplify the design. Each filetype is represented as a different subclass of AudioFile, and each of those has a play( ) method.
  • 7. Polymorphism AudioFile _ _init_ _( ) MP3File play( ) WAVFile play( ) OGGFile play( )
  • 8. Polymorphism class AudioFile: def _ _init_ _(self, filename): if not filename.endswith(self.ext): # THEN raise Exception(“Invalid format”) # ENDIF; self.filename = filename # END init() # END CLASS.
  • 9. Polymorphism class AudioFile: def _ _init_ _(self, filename): if not filename.endswith(self.ext): # THEN raise Exception(“Invalid format”) # ENDIF; self.filename = filename # END init() # END CLASS. Check if the file extension of the audio being played is a known extension, self.ext is set in each of the subclasses. Raise an exception if it’s an unknown file extension If it’s a known file extension, then assign the filename passed in to self.filename
  • 10. Polymorphism class MP3File(AudioFile): ext = “mp3” def play(self): print(“playing {} as mp3”.format(self.filename)) # END play # END CLASS.
  • 11. Polymorphism class WAVFile(AudioFile): ext = “wav” def play(self): print(“playing {} as wav”.format(self.filename)) # END play # END CLASS.
  • 12. Polymorphism class OGGFile(AudioFile): ext = “ogg” def play(self): print(“playing {} as ogg”.format(self.filename)) # END play # END CLASS.
  • 13. Polymorphism • Here’s how we run it: >>> mp3 = MP3File(“myfile.mp3”) >>> mp3.play() playing myfile.mp3 as mp3
  • 14. Polymorphism • Here’s another one: >>> wav = WAVFile(“myfile.wav”) >>> wav.play() playing myfile.wav as wav
  • 15. Polymorphism • Here’s an error: >>> ogg_declared_as_mp3 = MP3File("myfile.ogg") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "polymorphic_audio.py", line 4, in __init__ raise Exception("Invalid format") Exception: Invalid format
  • 16. etc.