dejoma
dejoma

Reputation: 494

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.

Upvotes: 4

Views: 8406

Answers (2)

Evren Bingøl
Evren Bingøl

Reputation: 1725

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

Upvotes: 2

Serge Ballesta
Serge Ballesta

Reputation: 148910

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

Upvotes: 6

Related Questions