python - Practical example of Polymorphism -


can please give me real life, practical example of polymorphism? professor tells me same old story have heard + operator. a+b = c , 2+2 = 4, polymorphism. can't associate myself such definition, since have read , re-read in many books.

what need real world example code, can associate with.

for example, here small example, in case want extend it.

>>> class person(object):     def __init__(self, name):         self.name = name  >>> class student(person):     def __init__(self, name, age):         super(student, self).__init__(name)         self.age = age 

check wikipedia example: helpful @ high level:

class animal:     def __init__(self, name):    # constructor of class         self.name = name     def talk(self):              # abstract method, defined convention         raise notimplementederror("subclass must implement abstract method")  class cat(animal):     def talk(self):         return 'meow!'  class dog(animal):     def talk(self):         return 'woof! woof!'  animals = [cat('missy'),            cat('mr. mistoffelees'),            dog('lassie')]  animal in animals:     print animal.name + ': ' + animal.talk()  # prints following: # # missy: meow! # mr. mistoffelees: meow! # lassie: woof! woof! 

notice following: animals "talk", talk differently. "talk" behaviour polymorphic in sense realized differently depending on animal. so, abstract "animal" concept not "talk", specific animals (like dogs , cats) have concrete implementation of action "talk".

similarly, "add" operation defined in many mathematical entities, in particular cases "add" according specific rules: 1+1 = 2, (1+2i)+(2-9i)=(3-7i).

polymorphic behaviour allows specify common methods in "abstract" level, , implement them in particular instances.

for example:

class person(object):     def pay_bill():         raise notimplementederror  class millionare(person):     def pay_bill():         print "here go! keep change!"  class gradstudent(person):     def pay_bill():         print "can owe ten bucks or dishes?" 

you see, millionares , grad students both persons. when comes paying bill, specific "pay bill" action different.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -