多态性的实例

Max*_*axx 58 python oop polymorphism

任何人都可以请给我一个现实生活,多态的实例吗?我的教授告诉我我一直听到的关于+操作员的老故事.a+b = c而且2+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
Run Code Online (Sandbox Code Playgroud)

Esc*_*alo 162

查看Wikipedia示例:它在高级别非常有用:

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!
Run Code Online (Sandbox Code Playgroud)

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

类似地,"添加"操作在许多数学实体中定义,但在特定情况下,您根据特定规则"添加":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?"
Run Code Online (Sandbox Code Playgroud)

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

  • 多态性在静态语言中更有意义,在这种语言中你不能在数组中有不同的类型吗?Python允许列表包含不同的类型,`[Cat(),Dog()]`,而在Java中,您必须将这些单独的动物实例定义为动物类型,将它们放在动物数组中,迭代它,调用它talk()方法.我不确定多态在Python中是如何帮助的? (8认同)
  • 使用`abstract`方法引发`NotImplementedError`会破坏`super`. (2认同)
  • @Pyderman继承是实现多态性的**手段之一. (2认同)
  • 您忘记在pay_bill方法中编写self参数了! (2认同)

Mat*_*hen 11

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


Kyu*_*une 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.

}
Run Code Online (Sandbox Code Playgroud)