【问题标题】:How to refactor polymorphic method to keep code DRY如何重构多态方法以保持代码 DRY
【发布时间】: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


【解决方案1】:

这不是“重复自己”的例子,因为Cat.show_affection() 所做的事情与Dog.show_affection() 不同。如果这两种方法相同,那么您可以通过在Animal 中定义一次实现来避免重复。但是由于您希望CatDog 具有不同的行为,因此正确的做法是在每个类中实现该方法。

一般:

  • 猫特有的行为应在Cat 中定义。
  • 应在Dog 中定义狗的特定行为。
  • 应在Animal 中定义适用于所有动物的行为。

【讨论】:

    猜你喜欢
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    相关资源
    最近更新 更多