Check out the Wikipedia example: it is very useful at a high level:
class Animal: def __init__(self, name):
Note the following: all animals "speak," but they speak differently. Thus, the “conversation” behavior is polymorphic in the sense that it is implemented differently depending on the animal. Thus, the abstract “animal” concept does not actually “speak,” but specific animals (for example, dogs and cats) have a concrete implementation of the “speak” action.
Similarly, the “add” operation is defined in many mathematical entities, but in certain cases you “add” in accordance with certain rules: 1 + 1 = 2, but (1 + 2i) + (2-9i) = (3-7i).
Polymorphic behavior allows you to specify common methods at the "abstract" level and implement them in certain cases.
In your example:
class Person(object): def pay_bill(): raise NotImplementedError class Millionare(Person): def pay_bill(): print "Here you go! Keep the change!" class GradStudent(Person): def pay_bill(): print "Can I owe you ten bucks or do the dishes?"
You see, millions and grad students are both people. But when it comes to paying the bill, their specific “pay the bill” action is different.
Escualo Sep 16 '10 at 6:16 2010-09-16 06:16
source share