Python 多态性的实例

Python 多态性的实例,python,oop,polymorphism,Python,Oop,Polymorphism,谁能给我一个现实生活中的多态性实例?我的教授告诉我关于+操作符的老故事a+b=c和2+2=4,这就是多态性。我真的无法将自己与这样的定义联系起来,因为我已经在很多书中反复阅读了这个定义 我需要的是一个带有代码的真实示例,这是我可以真正联想到的 例如,这里有一个小例子,以防您想要扩展它 >>> class Person(object): def __init__(self, name): self.name = name >>> cla

谁能给我一个现实生活中的多态性实例?我的教授告诉我关于
+
操作符的老故事
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

查看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!
注意以下几点:所有动物都会“说话”,但说话方式不同。因此,“说话”行为是多态性的,因为根据动物的不同,其实现方式也不同。因此,抽象的“动物”概念实际上并不是“说话”,而是特定的动物(如狗和猫)有一个“说话”行动的具体实施

类似地,“添加”操作在许多数学实体中定义,但在特定情况下,您可以根据特定规则“添加”: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?"

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

Python中一个常见的实际示例是。除了实际文件之外,还有其他几种类型,包括和,都是类似文件的。一种充当文件的方法也可以对它们起作用,因为它们支持所需的方法(例如:代码>读取< /代码>,<代码>写< /C++ >。< /P> < P>以上回答的多态性的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.

}

您是专门询问运算符多态性(也称为运算符重载)还是一般情况?一般情况下的多态性。使用
抽象
方法引发
未实现错误
会中断
超级
。这与继承有何不同,子类如何重写父类中的方法?@Pyderman继承是实现多态性的方法之一。在不能在数组中有不同类型的静态语言中,多态性是否更有意义?Python允许列表包含不同的类型,
[Cat(),Dog()]
,而在Java中,您必须将这些单独的动物实例定义为动物类型,将它们放在动物数组中,然后调用talk()方法对其进行迭代。我不知道多态性在Python中有什么帮助?您忘记在pay\u-bill方法中编写self参数了!