多态的实例

任何人都可以请给我一个现实生活,多态的实例吗?我的教授告诉我我一直听到的关于
+
操作员的老故事。
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中一个常见的实例是类文件对象。除了实际文件之外,其他几种类型(包括StringIO和BytesIO)都是文件类型。充当文件的方法也可以对它们起作用,因为它们支持所需的方法(例如,
read
write
)。     
上述答案中的多态性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 %sn", c.name_.c_str(), c.talk().c_str());
  printf("%s says %sn", 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 %sn", c2->name_.c_str(), c2->talk().c_str());
  printf("%s says %sn", 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.

}
    

要回复问题请先登录注册