The built-in function super() helps the inheritance in python. This function returns an object that represents the parent class and also gives access to the methods and properties of the parent class.
super()
It doesn't take any parameters. This method can work with multiple inheritances and it avoids the use of base class names explicitly.
Nothing is returned by this method. In python Method Resolution Order (MRO) outlines the order in which methods are inherited. The method in the derived calls is always called before the method of the base class.
class Mammals(object):
def __init__(self, mammalName):
print(mammalName, 'is a pet animal.')
class Cat(Mammals):
def __init__Cat has four legs.')
super().__init__('Cat')
c = Cat()
Output:
Cat is a pet animal.
class Animals:
def __init__(self, Animals):
print(Animals, 'is an animal.');
class Mammals(Animals):
def __init__(self, mammalName):
print(mammalName, 'is a pet animal.')
super().__init__(mammalName)
class NonWingedMammal(Mammals):
def __init__(self, NonWingedMammal):
print(NonWingedMammal, "can't fly.")
super().__init__(NonWingedMammal)
class NonMarineMammal(Mammals):
def __init__(self, NonMarineMammal):
print(NonMarineMammal, "can't swim.")
super().__init__(NonMarineMammal)
class Cat(NonMarineMammal, NonWingedMammal):
def __init__(self):
print('Cat has 4 legs.');
super().__init__('Cat')
c = Cat()
print('')
bat = NonMarineMammal('Bat')
Output:
Cat has 4 legs. Cat can't swim. Cat can't fly. Cat is a pet animal. Cat is an animal. Bat can't swim. Bat is a pet animal. Bat is an animal.