Can an method which is overridden still call the parent method if needed?


#1

Question

If a class overrides a method from the parent class, is it still possible to call the parent class method from the inheriting class if that is useful for the class to do?

Answer

Yes, the overriding method in the class can still call the method in the parent class if doing so will provide some benefit. Depending on whether you are using Python 2 or Python 3, the syntax for calling the parent class can be different. The following code example shows three different methods to make the call from the inheriting class B method to the parent class A method.

class A(object):
    def do_something(self, parm1):
        print("A - do_something - was passed " + str(parm1))

class B(A):
    def do_something(self, parm1):
        # Works for both Python 2 and 3
        A.do_something(self, parm1 + 1)

        # Python 2 - this only works if A inherits from object
        # super(B, self).do_something(parm1 + 1)

        # Python 3 -
        # super().do_something(parm1 + 1)
        print("B - do_something - was passed " + str(parm1))


obj = B()

obj.do_something(100)

#OUTPUTS:
# A - do_something - was passed 101
# B - do_something - was passed 100