Polymorphism
Another main principle of OOP is polymorphism.
Poly means many in Greek, while morphism means form.
So polymorphism means the ability to take various forms.
The idea is that you can use invoke same method regardless of what type of object it is, as long as the object implements the method.
For 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 person or dog or robot can run()
, they should be allowed to run()
!
This can be like inheritance, except that it is even more abstract. For example, the Character
class might not implement its attack()
method, but only stipulate that any subclassees must implement the attack()
method - they are free to do it however they like.
So the idea is to create an abstract class that defines methods (but does not necessarily implement them), and allow subclasses to implement these methods instead.
class Document:
def __init__(self, name):
self.name = name
def show(self):
raise NotImplementedError("Subclass must implement abstract method")
class Word(Document):
def show(self):
return "Word"
class Pdf(Document):
def show(self):
return "PDF"