0

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 call the parent's function as well.

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
Notebooked
  • 75
  • 7

2 Answers2

0

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
Sabil
  • 3,750
  • 1
  • 5
  • 16
0

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

class Bob(Person):
    def printp(self):
        super().printp()
        print('letter')
Nir H.
  • 550
  • 2
  • 9