【发布时间】:2016-09-23 13:15:24
【问题描述】:
这是我在学习 python 中的多态行为时使用的代码示例。 我的问题是:为什么我必须两次声明非常相似的 show_affect 函数?为什么不检查调用者(调用方法的实例)是否是 Dog,如果是猫,则做另一件事。
正如您在下面的示例代码中所见,show_affect 定义在继承自 Animal 的 Cat 和 Dog 类中。
为什么不在 Animal 类中声明 show_affection 但我不知道如何检查调用者。喜欢
def show_affection(self):
If caller is the Dog instance:
print("{0}.barks".format(self.name))
else:
print("{0}.wags tail".format(self.name))
这就是我所拥有的
class Animal(object):
def __init__(self, name):
self.name = name
def eat(self, food):
print("{0} eats {1}".format(self.name, food))
class Dog(Animal):
def fetch(self, thing):
print("{0} goes after the {1}".format(self.name, thing))
def show_affection(self):
print("{0} wags tail".format(self.name))
class Cat(Animal):
def swatstring(self):
print("{0} shreds the string".format(self.name))
def show_affection(self):
print("{0} purrs".format(self.name))
for a in (Dog('rover'), Cat('fluffy'), Cat('precious'), Dog('Scout')):
a.show_affection()
a.eat('bananas')
【问题讨论】:
-
这意味着
Animal类需要知道所有潜在的子类,这意味着它的可扩展性不是很好......我会警告不要过度应用这些原则,如 DRY .但是要回答您的问题,您可以测试type(self) == Dog
标签: python polymorphism