What is super() in Python?
The super() function in Python makes class inheritance more manageable and extensible. The function returns a temporary object that allows reference to a parent class by the keyword super.
The super() function has two major use cases:
- To avoid the usage of the super (parent) class explicitly.
- To enable multiple inheritances.
Code
Single inheritance
Consider the example below, where the parent class is referred to by the super keyword:
class Computer():def __init__(self, computer, ram, storage):self.computer = computerself.ram = ramself.storage = storage# Class Mobile inherits Computerclass Mobile(Computer):def __init__(self, computer, ram, storage, model):super().__init__(computer, ram, storage)self.model = modelApple = Mobile('Apple', 2, 64, 'iPhone X')print('The mobile is:', Apple.computer)print('The RAM is:', Apple.ram)print('The storage is:', Apple.storage)print('The model is:', Apple.model)
In the example above, Computer is a super (parent) class, while Mobile is a derived (child) class. The usage of the super keyword in line allows the child class to access the parent class’s init() property.
In other words, super() allows you to build classes that easily extend the functionality of previously built classes without implementing their functionality again.
Multiple inheritances
The following example shows how the Super() function is used to implement multiple inheritances:
class Animal:def __init__(self, animalName):print(animalName, 'is an animal.');# Mammal inherits Animalclass Mammal(Animal):def __init__(self, mammalName):print(mammalName, 'is a mammal.')super().__init__(mammalName)# CannotFly inherits Mammalclass CannotFly(Mammal):def __init__(self, mammalThatCantFly):print(mammalThatCantFly, "cannot fly.")super().__init__(mammalThatCantFly)# CannotSwim inherits Mammalclass CannotSwim(Mammal):def __init__(self, mammalThatCantSwim):print(mammalThatCantSwim, "cannot swim.")super().__init__(mammalThatCantSwim)# Cat inherits CannotSwim and CannotFlyclass Cat(CannotSwim, CannotFly):def __init__(self):print('I am a cat.');super().__init__('Cat')# Driver codecat = Cat()print('')bat = CannotSwim('Bat')
Consider the Cat class’s instantiation on line ; the following is the order of events that occur after it:
- The
Catclass is called first. - The
CannotSwimparent class is called since it appears beforeCannotFlyin the order of inheritance; this follows Python’s Method Resolution Order (MRO) which outlines the order in which methods are inherited. - The
CannotFlyclass is called. - The
Mammalclass is called. - Finally, the
Animalclass is called.
Next, consider the bat object. Bats are flying mammals, but they cannot swim, which is why it is instantiated with the CannotSwim class. The super function in the CannotSwim class invokes the Mammal class’s constructor after it. The Mammal class then invokes the Animal class’s constructor.
Free Resources