多态性的实例

时间:2010-09-16 06:03:32

标签: python oop polymorphism

有谁能请给我一个现实生活,多态性的实际例子?我的教授告诉我,我一直听到的关于+运算符的老故事。 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

3 个答案:

答案 0 :(得分:159)

查看维基百科示例:它在高层次上非常有用:

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!

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

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

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

对于你的例子:

class Person(object):
    def pay_bill(self):
        raise NotImplementedError

class Millionare(Person):
    def pay_bill(self):
        print "Here you go! Keep the change!"

class GradStudent(Person):
    def pay_bill(self):
        print "Can I owe you ten bucks or do the dishes?"

你看,百万人和研究生都是人。但是,当涉及到支付账单时,他们的具体“付账单”行动是不同的。

答案 1 :(得分:10)

Python中一个常见的例子是file-like objects。除了实际文件之外,其他几种类型(包括StringIOBytesIO)都是文件类型。充当文件的方法也可以对其起作用,因为它们支持所需的方法(例如readwrite)。

答案 2 :(得分:6)

上述答案中的多态性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.

}