gpt4 book ai didi

python - 多态性的实际例子

转载 作者:IT老高 更新时间:2023-10-28 20:23:28 25 4
gpt4 key购买 nike

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

最佳答案

查看 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!

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

同样,“加法”运算在许多数学实体中都有定义,但在特定情况下,您根据特定规则“加法”: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 - 多态性的实际例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3724110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com