多态性的实例

任何人都可以请给我一个真实的生活,多态的实际例子? 我的教授告诉我,我总是听到关于+运营商的那个老故事。 a+b = c2+2 = 4 ,所以这是多态性。 我真的不能把自己与这样一个定义联系起来,因为我已经在许多书中阅读和重读了这个定义。

我需要的是一个真实世界的代码示例,我可以真正联想到的东西。

例如,这里是一个小例子,以防万一你想扩展它。

 >>> 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 

检查维基百科的例子:它在很高的层次上非常有帮助:

 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! 

注意以下几点:所有的动物“说话”,但他们说话不一样。 “说话”行为因此是多形的,因为它根据动物而不同地实现 。 所以,抽象的“动物”概念实际上并不是“说话”,而是特定的动物(如狗和猫)具体实施“说话”的动作。

类似地,“添加”操作在许多math实体中定义,但是在特定情况下,根据特定规则“添加”:1 + 1 = 2,但是(1 + 2i)+(2-9i)=(3-7i )。

多态行为允许您在“抽象”级别指定常用方法,并在特定实例中实施它们。

举个例子:

 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?" 

你看,百万和gradle生都是人。 但是在支付账单方面,他们具体的“付账”行为是不一样的。

Python中一个常见的实例是类文件对象 。 除了实际的文件外,其他几种types,包括StringIO和BytesIO ,都是类似文件的。 作为文件的方法也可以作用于它们,因为它们支持所需的方法(例如readwrite )。

从上面的答案C ++的多态性的例子是:

 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. }