【问题标题】:Can a child be called from a parent in an inheritance relationship?可以从继承关系中的父级调用子级吗?
【发布时间】:2014-06-08 00:34:17
【问题描述】:

我在两个类之间有一个循环依赖关系,一个父类和子类在继承关系中。 Child 显然需要 Parent,但在这种情况下,Parent 还需要调用特定的 Child。

因为 Parent 和 Child 存储在两个不同的文件中,所以它们必须相互要求,这会产生循环依赖。我意识到这是一种不好的做法,但不知道如何解决它。

下面是一个与我正在做的类似的小例子。在这种情况下,Animal 是 Parent,Tiger 是一个孩子。

    class Animal:
       def can_beat_tiger(self):
         return not Tiger().can_eat(self)

    class Tiger(Animal):

有没有更好的方法来做到这一点?一些选项包括:

  • 使用组合。也许有一个较小的 Animal 类,其中包含一个 self.specific_animal 实例。
  • 从父项中删除子引用函数并复制到每个子项中。在这种情况下,这意味着将 can_beat_tiger() 函数移动到每个子 Animal。
  • 通过相关模块导入来处理它。 (循环依赖)

【问题讨论】:

  • can_beat_tiger() 的结果基于什么?
  • 为什么不能将类存储在同一个文件中?
  • Christian - 在这种情况下 can_beat_tiger() 是一个布尔值,True 或 False。 jwodder - 我在技术上可以,但担心它可能仍然是一种不受欢迎的代码气味。此外,随着代码库的扩展,这将是一个令人沮丧的限制。
  • 您对代码异味的看法是对的。这种情况表明您的设计存在缺陷。

标签: python inheritance composition


【解决方案1】:

我会通过覆盖来解决这个问题。基类将定义一个can_beat 函数,该函数始终返回False。让子类战斗。我认为这也不是很理想,因为子类需要相互了解。您还可以包含一个名为fightmaster 函数,它接受两个对象并根据您认为合适的任何标准计算结果。但是,这仍然需要包括所有可能的子类。

动物.py:

class Animal(object):
    def can_beat(self, other):
        return False

mouse.py:

import animal
import tiger


class Mouse(animal.Animal):
    def can_beat(self, other):
        if isinstance(other, tiger.Tiger):
            return False
        else:
            return True

tiger.py:

import animal
import mouse


class Tiger(animal.Animal):
    def can_beat(self, other):
        if isinstance(other, Tiger):
            return False
        elif isinstance(other, mouse.Mouse):
            return True
        else:
            return False

test.py:

from mouse import Mouse
from tiger import Tiger

if __name__ == '__main__':
    m = Mouse()
    t = Tiger()
    print m.can_beat(t)
    print t.can_beat(m)

注意:您通常可以使用from x import y 解决 not 的 ciruclar 引用导入问题。这样做会导致 Python 编译对象,这会导致很多问题。您可以使用import x 来解决这个问题。

【讨论】:

    猜你喜欢
    • 2015-06-09
    • 2018-09-17
    • 2018-06-14
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多