SlideShare a Scribd company logo
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.
Ad

More Related Content

What's hot (20)

Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
XML and DTD
XML and DTDXML and DTD
XML and DTD
Jussi Pohjolainen
 
Python Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaPython Collections Tutorial | Edureka
Python Collections Tutorial | Edureka
Edureka!
 
Files in Python.pptx
Files in Python.pptxFiles in Python.pptx
Files in Python.pptx
Koteswari Kasireddy
 
Python-Inheritance.pptx
Python-Inheritance.pptxPython-Inheritance.pptx
Python-Inheritance.pptx
Karudaiyar Ganapathy
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Python ppt
Python pptPython ppt
Python ppt
Mohita Pandey
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
vikram mahendra
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
baabtra.com - No. 1 supplier of quality freshers
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
Hector Canto
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
Kumar
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
Mohammed Sikander
 
Operator Overloading In Python
Operator Overloading In PythonOperator Overloading In Python
Operator Overloading In Python
Simplilearn
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
Sanjit Shaw
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
Simplilearn
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
Binay Kumar Ray
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Python Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaPython Collections Tutorial | Edureka
Python Collections Tutorial | Edureka
Edureka!
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
vikram mahendra
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Edureka!
 
Effective testing with pytest
Effective testing with pytestEffective testing with pytest
Effective testing with pytest
Hector Canto
 
Files in c++ ppt
Files in c++ pptFiles in c++ ppt
Files in c++ ppt
Kumar
 
Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...Python File Handling | File Operations in Python | Learn python programming |...
Python File Handling | File Operations in Python | Learn python programming |...
Edureka!
 
Operator Overloading In Python
Operator Overloading In PythonOperator Overloading In Python
Operator Overloading In Python
Simplilearn
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
Sanjit Shaw
 
Packages In Python Tutorial
Packages In Python TutorialPackages In Python Tutorial
Packages In Python Tutorial
Simplilearn
 

Viewers also liked (12)

Object-Orientated Design
Object-Orientated DesignObject-Orientated Design
Object-Orientated Design
Damian T. Gordon
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
Damian T. Gordon
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
Damian T. Gordon
 
Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party Libraries
Damian T. Gordon
 
Python: Access Control
Python: Access ControlPython: Access Control
Python: Access Control
Damian T. Gordon
 
Python: The Iterator Pattern
Python: The Iterator PatternPython: The Iterator Pattern
Python: The Iterator Pattern
Damian T. Gordon
 
Python: Design Patterns
Python: Design PatternsPython: Design Patterns
Python: Design Patterns
Damian T. Gordon
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
Damian T. Gordon
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
Damian T. Gordon
 
Python: Manager Objects
Python: Manager ObjectsPython: Manager Objects
Python: Manager Objects
Damian T. Gordon
 
Python: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingPython: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented Programming
Damian T. Gordon
 
The Extreme Programming (XP) Model
The Extreme Programming (XP) ModelThe Extreme Programming (XP) Model
The Extreme Programming (XP) Model
Damian T. Gordon
 
Introduction to Python programming
Introduction to Python programmingIntroduction to Python programming
Introduction to Python programming
Damian T. Gordon
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
Damian T. Gordon
 
Python: Third-Party Libraries
Python: Third-Party LibrariesPython: Third-Party Libraries
Python: Third-Party Libraries
Damian T. Gordon
 
Python: The Iterator Pattern
Python: The Iterator PatternPython: The Iterator Pattern
Python: The Iterator Pattern
Damian T. Gordon
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
Damian T. Gordon
 
Python: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented ProgrammingPython: Migrating from Procedural to Object-Oriented Programming
Python: Migrating from Procedural to Object-Oriented Programming
Damian T. Gordon
 
The Extreme Programming (XP) Model
The Extreme Programming (XP) ModelThe Extreme Programming (XP) Model
The Extreme Programming (XP) Model
Damian T. Gordon
 
Ad

More from Damian T. Gordon (20)

Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
TRIZ: Theory of Inventive Problem Solving
TRIZ: Theory of Inventive Problem SolvingTRIZ: Theory of Inventive Problem Solving
TRIZ: Theory of Inventive Problem Solving
Damian T. Gordon
 
Some Ethical Considerations of AI and GenAI
Some Ethical Considerations of AI and GenAISome Ethical Considerations of AI and GenAI
Some Ethical Considerations of AI and GenAI
Damian T. Gordon
 
Some Common Errors that Generative AI Produces
Some Common Errors that Generative AI ProducesSome Common Errors that Generative AI Produces
Some Common Errors that Generative AI Produces
Damian T. Gordon
 
The Use of Data and Datasets in Data Science
The Use of Data and Datasets in Data ScienceThe Use of Data and Datasets in Data Science
The Use of Data and Datasets in Data Science
Damian T. Gordon
 
A History of Different Versions of Microsoft Windows
A History of Different Versions of Microsoft WindowsA History of Different Versions of Microsoft Windows
A History of Different Versions of Microsoft Windows
Damian T. Gordon
 
Writing an Abstract: A Question-based Approach
Writing an Abstract: A Question-based ApproachWriting an Abstract: A Question-based Approach
Writing an Abstract: A Question-based Approach
Damian T. Gordon
 
Using GenAI for Universal Design for Learning
Using GenAI for Universal Design for LearningUsing GenAI for Universal Design for Learning
Using GenAI for Universal Design for Learning
Damian T. Gordon
 
A CheckSheet for Inclusive Software Design
A CheckSheet for Inclusive Software DesignA CheckSheet for Inclusive Software Design
A CheckSheet for Inclusive Software Design
Damian T. Gordon
 
A History of Versions of the Apple MacOS
A History of Versions of the Apple MacOSA History of Versions of the Apple MacOS
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
68 Ways that Data Science and AI can help address the UN Sustainability Goals68 Ways that Data Science and AI can help address the UN Sustainability Goals
68 Ways that Data Science and AI can help address the UN Sustainability Goals
Damian T. Gordon
 
Copyright and Creative Commons Considerations
Copyright and Creative Commons ConsiderationsCopyright and Creative Commons Considerations
Copyright and Creative Commons Considerations
Damian T. Gordon
 
Exam Preparation: Some Ideas and Suggestions
Exam Preparation: Some Ideas and SuggestionsExam Preparation: Some Ideas and Suggestions
Exam Preparation: Some Ideas and Suggestions
Damian T. Gordon
 
Studying and Notetaking: Some Suggestions
Studying and Notetaking: Some SuggestionsStudying and Notetaking: Some Suggestions
Studying and Notetaking: Some Suggestions
Damian T. Gordon
 
The Growth Mindset: Explanations and Activities
The Growth Mindset: Explanations and ActivitiesThe Growth Mindset: Explanations and Activities
The Growth Mindset: Explanations and Activities
Damian T. Gordon
 
Hyperparameter Tuning in Neural Networks
Hyperparameter Tuning in Neural NetworksHyperparameter Tuning in Neural Networks
Hyperparameter Tuning in Neural Networks
Damian T. Gordon
 
Early 20th Century Modern Art: Movements and Artists
Early 20th Century Modern Art: Movements and ArtistsEarly 20th Century Modern Art: Movements and Artists
Early 20th Century Modern Art: Movements and Artists
Damian T. Gordon
 
An Introduction to Generative Artificial Intelligence
An Introduction to Generative Artificial IntelligenceAn Introduction to Generative Artificial Intelligence
An Introduction to Generative Artificial Intelligence
Damian T. Gordon
 
An Introduction to Green Computing with a fun quiz.
An Introduction to Green Computing with a fun quiz.An Introduction to Green Computing with a fun quiz.
An Introduction to Green Computing with a fun quiz.
Damian T. Gordon
 
Introduction to Sustainability and the UN Sustainable Development Goals
Introduction to Sustainability and the UN Sustainable Development GoalsIntroduction to Sustainability and the UN Sustainable Development Goals
Introduction to Sustainability and the UN Sustainable Development Goals
Damian T. Gordon
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
TRIZ: Theory of Inventive Problem Solving
TRIZ: Theory of Inventive Problem SolvingTRIZ: Theory of Inventive Problem Solving
TRIZ: Theory of Inventive Problem Solving
Damian T. Gordon
 
Some Ethical Considerations of AI and GenAI
Some Ethical Considerations of AI and GenAISome Ethical Considerations of AI and GenAI
Some Ethical Considerations of AI and GenAI
Damian T. Gordon
 
Some Common Errors that Generative AI Produces
Some Common Errors that Generative AI ProducesSome Common Errors that Generative AI Produces
Some Common Errors that Generative AI Produces
Damian T. Gordon
 
The Use of Data and Datasets in Data Science
The Use of Data and Datasets in Data ScienceThe Use of Data and Datasets in Data Science
The Use of Data and Datasets in Data Science
Damian T. Gordon
 
A History of Different Versions of Microsoft Windows
A History of Different Versions of Microsoft WindowsA History of Different Versions of Microsoft Windows
A History of Different Versions of Microsoft Windows
Damian T. Gordon
 
Writing an Abstract: A Question-based Approach
Writing an Abstract: A Question-based ApproachWriting an Abstract: A Question-based Approach
Writing an Abstract: A Question-based Approach
Damian T. Gordon
 
Using GenAI for Universal Design for Learning
Using GenAI for Universal Design for LearningUsing GenAI for Universal Design for Learning
Using GenAI for Universal Design for Learning
Damian T. Gordon
 
A CheckSheet for Inclusive Software Design
A CheckSheet for Inclusive Software DesignA CheckSheet for Inclusive Software Design
A CheckSheet for Inclusive Software Design
Damian T. Gordon
 
A History of Versions of the Apple MacOS
A History of Versions of the Apple MacOSA History of Versions of the Apple MacOS
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
68 Ways that Data Science and AI can help address the UN Sustainability Goals68 Ways that Data Science and AI can help address the UN Sustainability Goals
68 Ways that Data Science and AI can help address the UN Sustainability Goals
Damian T. Gordon
 
Copyright and Creative Commons Considerations
Copyright and Creative Commons ConsiderationsCopyright and Creative Commons Considerations
Copyright and Creative Commons Considerations
Damian T. Gordon
 
Exam Preparation: Some Ideas and Suggestions
Exam Preparation: Some Ideas and SuggestionsExam Preparation: Some Ideas and Suggestions
Exam Preparation: Some Ideas and Suggestions
Damian T. Gordon
 
Studying and Notetaking: Some Suggestions
Studying and Notetaking: Some SuggestionsStudying and Notetaking: Some Suggestions
Studying and Notetaking: Some Suggestions
Damian T. Gordon
 
The Growth Mindset: Explanations and Activities
The Growth Mindset: Explanations and ActivitiesThe Growth Mindset: Explanations and Activities
The Growth Mindset: Explanations and Activities
Damian T. Gordon
 
Hyperparameter Tuning in Neural Networks
Hyperparameter Tuning in Neural NetworksHyperparameter Tuning in Neural Networks
Hyperparameter Tuning in Neural Networks
Damian T. Gordon
 
Early 20th Century Modern Art: Movements and Artists
Early 20th Century Modern Art: Movements and ArtistsEarly 20th Century Modern Art: Movements and Artists
Early 20th Century Modern Art: Movements and Artists
Damian T. Gordon
 
An Introduction to Generative Artificial Intelligence
An Introduction to Generative Artificial IntelligenceAn Introduction to Generative Artificial Intelligence
An Introduction to Generative Artificial Intelligence
Damian T. Gordon
 
An Introduction to Green Computing with a fun quiz.
An Introduction to Green Computing with a fun quiz.An Introduction to Green Computing with a fun quiz.
An Introduction to Green Computing with a fun quiz.
Damian T. Gordon
 
Introduction to Sustainability and the UN Sustainable Development Goals
Introduction to Sustainability and the UN Sustainable Development GoalsIntroduction to Sustainability and the UN Sustainable Development Goals
Introduction to Sustainability and the UN Sustainable Development Goals
Damian T. Gordon
 
Ad

Recently uploaded (20)

SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 

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.