Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 e.g. 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.

like image 702
dejoma Avatar asked Sep 17 '25 03:09

dejoma


2 Answers

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
like image 136
Serge Ballesta Avatar answered Sep 18 '25 16:09

Serge Ballesta


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
like image 25
user498584 Avatar answered Sep 18 '25 18:09

user498584