Python 多态的实际例子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3724110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Practical example of Polymorphism
提问by Maxx
Can anyone please give me a real life, practical example of Polymorphism? My professor tells me the same old story I have heard always about the +operator. a+b = cand 2+2 = 4, so this is polymorphism. I really can't associate myself with such a definition, since I have read and re-read this in many books.
谁能给我一个真实的、实际的多态性例子?我的教授给我讲了我一直听到的关于+接线员的老故事。a+b = c并且2+2 = 4,所以这是多态。我真的无法将自己与这样的定义联系起来,因为我已经阅读并重新阅读了许多书籍。
What I need is a real world example with code, something that I can truly associate with.
我需要的是一个真实世界的代码示例,我可以真正将其联系起来。
For example, here is a small example, just in case you want to extend it.
例如,这里有一个小例子,以防万一你想扩展它。
>>> 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
采纳答案by Escualo
Check the Wikipedia example: it is very helpful at a high level:
检查维基百科示例:它在高层次上非常有帮助:
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!
Notice the following: all animals "talk", but they talk differently. The "talk" behaviour is thus polymorphic in the sense that it is realized differently depending on the animal. So, the abstract "animal" concept does not actually "talk", but specific animals (like dogs and cats) have a concrete implementation of the action "talk".
请注意以下几点:所有动物都在“说话”,但它们的说话方式不同。因此,“说话”行为是多态的,因为它根据动物的不同而实现不同。所以,抽象的“动物”概念实际上并不是“说话”,而是特定的动物(如狗和猫)对“说话”动作有具体的实现。
Similarly, the "add" operation is defined in many mathematical entities, but in particular cases you "add" according to specific rules: 1+1 = 2, but (1+2i)+(2-9i)=(3-7i).
类似地,许多数学实体中都定义了“加”运算,但在特定情况下,您可以根据特定规则“加”:1+1 = 2,但是 (1+2i)+(2-9i)=(3-7i )。
Polymorphic behaviour allows you to specify common methods in an "abstract" level, and implement them in particular instances.
多态行为允许您在“抽象”级别指定通用方法,并在特定实例中实现它们。
For your example:
对于您的示例:
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?"
You see, millionares and grad students are both persons. But when it comes to paying a bill, their specific "pay the bill" action is different.
你看,百万富翁和研究生都是人。但是说到付账,他们具体的“付账”动作就不一样了。
回答by Matthew Flaschen
A common real example in Python is file-like objects. Besides actual files, several other types, including StringIOand BytesIO, are file-like. A method that acts as files can also act on them because they support the required methods (e.g. read, write).
Python 中一个常见的真实示例是类文件对象。除了实际的文件,其他几种类型,包括StringIO和BytesIO,都是类似文件的。充当文件的方法也可以作用于它们,因为它们支持所需的方法(例如read、write)。
回答by Kyuubi Kitsune
A C++ example of polymorphism from the above answer would be:
来自上述答案的 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.
}

