Home > Software engineering >  How to 'add on' to function in parent class in Python? [duplicate]
How to 'add on' to function in parent class in Python? [duplicate]

Time:09-22

I have a parent class with a function. There is a subclass of the parent class that has the same function name, but instead of overriding it as usual, I would like to run the subclass's function after the parent class's function is run.

Here is an example:

class Person:
    def __init__(self,p):
        self.p = p
    def printp(self):
        print(self.p)

class Bob(Person):
    def printp(self):
        print('letter')
        
b = Bob('p')
b.printp()

Currently, this prints 'p'. I would like it to print:

p
letter

I have tried wrappers, but I can't get those to work.

CodePudding user response:

This could be one solution:

class Person:
    def __init__(self,p):
        self.p = p
    def printp(self):
        print(self.p)

class Bob(Person):
    def printp(self):
        # here I use super to call parent class printp()
        super().printp()
        print('letter')
        
b = Bob('p')
b.printp()

Output:

p
letter

CodePudding user response:

You can call the parent's method from the child's method like so:

class Bob(Person):
    def printp(self):
        super().printp()
        print('letter')
  • Related