Python – Refer Parent Class – super() Function with Examples

super() function is used to find the a proxy object that allows you to refer parent class by ‘super’ in Python for the given input.

super() function is a part of Python Built-in Functions.

Syntax of super() Function

The syntax of super() function in Python is:

super()

 

Compatibility

super() function is available and compatible with both Python 2.x and 3.x.

 

Return Value of super() Function in Python

super() function returns a proxy object that allows you to refer parent class by ‘super’ for the given input.

 

Python super() Function Example 1

class Parent:
  def __init__(self, txt):
    self.message = txt

  def printmessage(self):
    print(self.message)

class Child(Parent):
  def __init__(self, txt):
    super().__init__(txt)

x = Child("Hello, and welcome!")

x.printmessage()

Output:

Hello, and welcome!

Python super() Function Example 2

class Mammal(object):
  def__init__(self, mammalName):
    print(mammalName, 'is a warm-blooded animal.')
    
class Dog(Mammal):
  def__init__(self):
    print('Dog has four legs.')
    super().__init__('Dog')
    
d1 = Dog()

Output:

Dog has four legs.
Dog is a warm-blooded animal.