Today I came across the following piece of code when I was looking at a PyTorch nueral network:
class NeuralNet(nn.Module):
def __init__(self, input_size, hidden_size, num_classes):
super(NeuralNet, self).__init__()
self.l1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.l2 = nn.Linear(hidden_size, num_classes)
...
I was curious about this line super(NeuralNet, self).__init__()
. I've generally just used super().__init__()
. What's the point of calling super()
with these two arguments?
super()
is used to call methods from a parent or sibling class, especially in the init method of a class. It ensures that the parent class is properly initialized before executing more specific initializations in a child class.
Turns out in Python 2 and early versions of Python 3, the explicit form super(Child, self).__init__()
is used to specify the class and instance context and using this form allows for compatibility and in complex multiple inheritance scenarios.
Seem this explicit form helps manage the Method Resolution Order (MRO) in multiple inheritance scenarios, where different classes might define methods with the same name.
But in modern Python 3 code, we can just use super()
without parameters to achieve the same effect because Python 3's super()
automatically handles the class and instance context.
super()
is used to call methods from a parent or sibling class, especially in the init method of a class. It ensures that the parent class is properly initialized before executing more specific initializations in a child class.
Simple Example
Below is a simple example where Tesla
inherits from Car
:
class Car:
def __init__(self):
self.attributes = 'Car attributes initialized'
print("Car constructor")
class Tesla(Car):
def __init__(self):
super().__init__()
print("Tesla constructor")
When an instance of Tesla is created, the output shows that the parent class is initialized first, followed by the child class.
tesla = Tesla()
# outputs
# Car constructor
# Tesla constructor
The explicit form will also achieve the same result:
class Ford(Car):
def __init__(self):
super(Ford, self).__init__()
print("Ford constructor")
This Colab notebook has all the code examples and inheritence experiments.