可以在继承关系中从父级调用子级吗?

时间:2014-06-08 00:34:17

标签: python inheritance composition

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

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

下面是一个与我正在做的类似的小例子。在这种情况下,动物是父母,虎是一个孩子。

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

    class Tiger(Animal):

有更好的方法吗?一些选项包括:

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

1 个答案:

答案 0 :(得分:1)

我用覆盖来解决这个问题。基类将定义can_beat函数,该函数始终返回False。让孩子上课战斗。我不认为这也是非常理想的,因为孩子们需要彼此了解。您还可以包含一个名为fight函数,该函数接受两个对象并根据您认为合适的条件计算结果。但是,这仍然需要包括所有可能的子类。

animal.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通过而非解决ciruclar引用导入问题。这样做会导致Python编译对象,这会导致很多问题。您可以使用import x来解决这个问题。