Advanced Lesson 3
Advanced Object-Oriented Programming
Chapter 2: Polymorphism
Duck typing
In Python, you can take the concept of an abstract class even further.
Some classes might end up being so abstract that it does not implement anything (i.e. all methods are abstract, and it does not have any other attributes). In this case, then there might be no real value to even subclass it. You can just implement all the required methods and it will still work!
For example, in our example from Core Lesson 10, I said that a Person
can use its weapon to hurt()
any victim, whatever the weapon is. We can make this even more general - the object does not even need to be a weapon! As long as the object can be used to hurt()
someone, the Person
can use it! It can be a gun, a hammer, a frying pan, a chair, a hurtful remark, a snake, or a dumbbell. As long as these objects implement the hurt()
method, it can be used!
As another example, if we want an object to run()
, it does not matter whether that object is a person or a dog or a robot. As long as the object can run()
, they should be allowed to run()
!
This form of polymorphism is also known as duck typing.
The main idea behind duck typing is that “if an object walks like a duck and quacks like a duck, then it must be a duck”.
Rather than classifying an object by their type, you now classify an object by their behaviour. If all we need is an object that is able to quack()
, then it does not matter what type of object it is! A bit like how you would hire someone for a job based on their abilities, rather than who or what they are.