多态性实例

2024-03-28 15:49:16 发布

您现在位置:Python中文网/ 问答频道 /正文

有谁能给我一个真实的,多态性的例子吗?我的教授给我讲了一个关于+运算符的老故事。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

Tags: 代码nameselfage定义initdef运算符
3条回答

Python中一个常见的实际例子是file-like objects。除了实际的文件外,还有一些其他类型的文件,包括StringIOBytesIO,类似于文件。充当文件的方法也可以对其执行操作,因为它们支持所需的方法(例如readwrite)。

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

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!

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

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

你看,百万富翁和研究生都是人。但在付账方面,他们具体的“付账”行动则有所不同。

以上回答的多态性的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.

}

相关问题 更多 >