Python call super method | Example code

The super() function lets you run a parent class function inside the child class. Python super method returns a proxy object that delegates method calls to a parent or sibling class of type. It is used to access inherited methods that have been overridden in a class.

Python call super method example

Simple example code.

class Parent(object):
    def __init__(self, age):
        self.age = age

    def func(self):
        print(f"Hi, my age is {self.age}!")


class Child(Parent):
    def __init__(self, age):
        # use the super to run the parent class __init__ function to set the childs' name
        super().__init__(age)


dad = Parent(50)
kid = Child(18)

dad.func()
kid.func()  # The kid inherits it from the dad, so I could run it like that too

Output:

Python call super method

How do I call a parent class’s method from a child class in Python?

Answer: Use the super() function: Return a proxy object that delegates method calls to a parent or sibling class of type.

class A(object):
    def foo(self):
        print ("foo")


class B(A):
    def foo(self):
        super(B, self).foo()  # calls 'A.foo()'


myB = B()
myB.foo()

Output: foo

How to call a super method from the grandchild class?

Answer: Here is an example of call a super method from the grandchild class.

class Grandparent(object):
    def my_method(self):
        print("Grandparent")


class Parent(Grandparent):
    def my_method(self):
        print("Parent")


class Child(Parent):
    def my_method(self):
        print("Hello Grandparent")
        Grandparent.my_method(self)


obj1 = Child()
obj1.my_method()

Output:

Hello Grandparent
Grandparent

Do comment if you have any doubts and suggestions on this Python method tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.