A practical example of polymorphism

Can someone give me a real life, practical example of polymorphism? My professor tells me the same old story that I always heard about the + operator. a+b = c and 2+2 = 4 , so this is a polymorphism. I really cannot relate to this definition, as I have read and re-read it in many books.

I need a real world example with code that I can really communicate with.

For example, here is a small example, just in case you want to expand 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 
+47
python polymorphism oop
Sep 16 '10 at 6:03
source share
3 answers

Check out the Wikipedia example: it is very useful at a high level:

 class Animal: def __init__(self, name): # Constructor of the class self.name = name def talk(self): # Abstract method, defined by convention only 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')] for animal in animals: print animal.name + ': ' + animal.talk() # prints the following: # # Missy: Meow! # Mr. Mistoffelees: Meow! # Lassie: Woof! Woof! 

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.

+146
Sep 16 '10 at 6:16
source share

A common real-life example in Python is file objects . Besides the actual files, several other types, including StringIO and BytesIO , are file types. A method that acts like files can also act on them, because they support the required methods (for example, read , write ).

+10
Sep 16 '10 at 6:21
source share

An example of C ++ polymorphism from the answer above would be:

 class Animal { public: Animal(const std::string& name) : name_(name) {} virtual ~Animal() {} virtual std::string talk() = 0; std::string name_; }; class Dog : public Animal { public: virtual std::string talk() { return "woof!"; } }; class Cat : public Animal { public: virtual std::string talk() { return "meow!"; } }; void main() { Cat c("Miffy"); Dog d("Spot"); // This shows typical inheritance and basic polymorphism, as the objects are typed by definition and cannot change types at runtime. printf("%s says %s\n", c.name_.c_str(), c.talk().c_str()); printf("%s says %s\n", d.name_.c_str(), d.talk().c_str()); Animal* c2 = new Cat("Miffy"); // polymorph this animal pointer into a cat! Animal* d2 = new Dog("Spot"); // or a dog! // This shows full polymorphism as the types are only known at runtime, // and the execution of the "talk" function has to be determined by // the runtime type, not by the type definition, and can actually change // depending on runtime factors (user choice, for example). printf("%s says %s\n", c2->name_.c_str(), c2->talk().c_str()); printf("%s says %s\n", d2->name_.c_str(), d2->talk().c_str()); // This will not compile as Animal cannot be instanced with an undefined function Animal c; Animal* c = new Animal("amby"); // This is fine, however Animal* a; // hasn't been polymorphed yet, so okay. } 
+5
Dec 01 '14 at 7:09
source share



All Articles