Python Jumpstart by Building 10 Apps Transcripts
Chapter: App 7: Wizard Battle App
Lecture: Concept: Polymorphism
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
Let's look at the final core concept in this object oriented wizard game called polymorphism. Now you can see that we have a list of diverse creatures,
0:10
we have small animals, creatures, dragons, wizards and so on, and as you saw on a previous examples and you can see in the note on the left here,
0:18
all of these objects all of these classes, small animal, dragon and wizard, all derive from creature. Below we have a wizard named Gandolf.
0:27
and if he is going to go on some kind of a rampage and just start attacking all the creatures he would say for c in creatures wizard.attack c,
0:34
now when we write that attack method, we don't care or usually want to know, it's usually a negative thing to actually know whether it's a dragon
0:42
a small animal or just a creature because we can leverage the fact that all of these derived from creature
0:49
we can just work with the common functionality, the fields and the methods on the creature class and it doesn't matter
0:56
what type of derived object we pass, it's a small animal, a dragon, we can still fight it just the same, we don't have to rewrite our code,
1:04
and that's fantastic, that lets us as we evolve our application create more specialization other types of objects,
1:11
later in the game we want to add some kind of like water monster to attack the wizard when he is out in the ocean or something
1:18
as long as that thing derives from creature, we potentially don't have to rewrite the code that handles wizard's battling water monsters
1:26
it's just using this base class. So that's a really powerful feature. One other concept closely related to this is something called duck typing,
1:33
in statically typed compiled languages like C#, Java, C++ and so on, you absolutely must have these objects derived from creature
1:44
or trying to pass them to the attack method which assumes it takes a creature or literally not compile, your code won't run ever.
1:50
In Python it's not like that, Python uses something called duck typing and as long as the shape of the pieces of the creature class
2:00
that the attack method assumes are there, get defensive roll, name, as long as the types you pass match that,
2:08
you technically can use it here, and that is called duck typing, it's like if it acts like a creature, if it looks like a creature, it is a creature,
2:14
but I still encourage you to create these object hierarchies as it helps reduce code duplication, it helps with maintenance
2:19
and it's generally just the right thing to do.