在 Python 中调用父 class 中的子方法

Calling a child method in a parent class in Python

注:不是关于Calling a parent method in a child class .super()

我有三个 class,比方说 ParentChild1Child2Child1 和 2 都有方法 Cry()Parent class 有另一种方法,例如MakeChildrenStopCry() 其中 Cry() 被调用。但是,Parent class 没有方法 Cry()。我需要在 Parent class 中定义 Cry() 吗?

因为我没有父 class 的任何对象,而且我总是使用子 classes,所以我简单地创建了 'empty functions' 因为继承将否决这些空函数使用 Child classes.

中的函数
def MakeChildrenStopCry(self):
   if self.Cry():
    self.DoWhateverToStopCry(self)
def Cry(self)
   return()

完整示例代码 you can check this 但我认为以上内容应该很清楚。

这不会在我的代码中造成任何问题,我只是想知道正常情况下会做什么,或者以不同的方式设置我的代码是否更好。

Python 在这个水平上是相当有信心的程序员。您始终可以从 class 调用 cry 方法,即使它未在 class 中定义。 Python 只会相信您提供一个对象,该对象在调用时知道 cry 方法。

所以这很好:

class Parent:
    def makeChildrenStopCry(self):
        if self.cry():
            self.doWhateverToStopCry()

class Children(Parent):
    crying = False
    def makeCry(self):
        self.crying = True
    def doWhateverToStopCry(self):
        self.crying = False
    def cry(self):
        return self.crying

它在交互式会话中给出:

>>> child = Children()
>>> child.makeCry()
>>> print(child.crying)
True
>>> child.makeChildrenStopCry()
>>> print(child.crying)
False

如果父类有抽象方法怎么办?

class Parent:
    def cry(self):
        raise NotImplementedError

    def doWhateverToStopCry(self):
        raise NotImplementedError

    def makeChildrenStopCry(self):
        if self.cry():
            self.doWhateverToStopCry()

class Children(Parent):
    crying = False
    def makeCry(self):
        self.crying = True
    def doWhateverToStopCry(self):
        self.crying = False
    def cry(self):
        return self.crying