简体   繁体   中英

Calling a child method in a parent class in Python

Note: It is not about Calling a parent method in a child class .super()

I have three classes, let's say Parent , Child1 and Child2 . Child1 and 2 both have method Cry() and Parent class has another method eg MakeChildrenStopCry() in which Cry() is called. However, Parent class does not have method Cry() . Do I need to define Cry() in the Parent class?

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.

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. You can always call a cry method from a class even if it is not defined in the class. Python will just trust you to provide an object that knows of the cry method at the time if will be called.

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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