简体   繁体   English

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

[英]Calling a child method in a parent class in Python

Note: It is not about Calling a parent method in a child class .super()注意:这不是在子类中调用父方法 .super()

I have three classes, let's say Parent , Child1 and Child2 .我有三个类,比方说, ParentChild1Child2 Child1 and 2 both have method Cry() and Parent class has another method eg MakeChildrenStopCry() in which Cry() is called. Child1和 2 都有Cry()方法,而Parent类有另一个方法,例如MakeChildrenStopCry() ,其中调用了Cry() However, Parent class does not have method Cry() .但是, Parent类没有方法Cry() Do I need to define Cry() in the Parent class?我需要在Parent类中定义Cry()吗?

Since I do not have any objects of the parent class and I always use the child classes, I simply created 'empty functions' since the inheritance will just overrule these empty functions with the functions from the Child classes.因为我没有父类的任何对象并且我总是使用子类,所以我只是创建了“空函数”,因为继承只会用Child类的函数来覆盖这些空函数。

def MakeChildrenStopCry(self):
   if self.Cry():
    self.DoWhateverToStopCry(self)
def Cry(self)
   return()

For full sample code you can check this but I think the above should be clear.对于完整的示例代码,您可以查看此内容,但我认为上述内容应该很清楚。

This is not causing any problems in my code, I just want to know what is done normally or if it is maybe better to setup my code differently.这不会在我的代码中造成任何问题,我只是想知道什么是正常完成的,或者以不同的方式设置我的代码是否更好。

Python is rather programmer confident at this level. Python 在这个层面上对程序员相当有信心。 You can always call a cry method from a class even if it is not defined in the class.即使类中未定义,您始终可以从类中调用cry方法。 Python will just trust you to provide an object that knows of the cry method at the time if will be called. Python 只会相信您会提供一个对象,该对象在调用 if 时知道cry方法。

So this is perfectly fine:所以这完全没问题:

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

It gives in an interactive session:它在交互式会话中给出:

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

What if parent has abstract methods?如果 parent 有抽象方法怎么办?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM