Introduction
Original article lies here!
https://www.programiz.com/python-programming/methods/built-in/super
When I was reading the other's code, I didn't get how the method super()
was used, so I decided to save a time a bit for doing research about this.
What is super()?
The super()
built-in returns a proxy object that allows you to refer parent class by super
.
Normally in Python, this function has two major use cases:
1. allows us to avoid using base class explicitly
2. working with multiple inheritance
So, in this article, I will show the use cases with the actual code using python3.6!
Ex.1 : super() with Single Inheritance
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')
dog_1 = Dog()
# output
Dog has four legs.
Dog is a warm-blooded animal.
Why is this happy for us??
yeah, that is the same question I had at first time when I read the article, let me a bit elaborate.
class Dog(NotCat):
def __init__(self):
print('Dog has four legs.')
# no need to change this
super().__init__('Dog')
So, for example, when we are refactoring the code and if someone wants to change the name of the base class, thanks to the super() method, it won't require our workload so much!
Ex.2 : super() with Multiple Inheritance
class Animal:
def __init__(self, animalName):
print(animalName, 'is an animal')
class Mammal(Animal):
def __init__(self, mammalName):
print(mammalName, 'is a warm-blooded animal.')
super().__init__(mammalName)
class NonWingedMammal(Mammal):
def __init__(self, NonWingedMammalName):
print(NonWingedMammalName, 'cannnot fly')
super().__init__(NonWingedMammalName)
class NonMarineMammal(Mammal):
def __init__(self, NonMarineMammalName):
print(NonMarineMammalName, 'cannot swim')
super().__init__(NonMarineMammalName)
class Dog(NonMarineMammal, NonWingedMammal):
def __init__(self):
print('Dog has four legs')
super().__init__('Dog')
dog = Dog()
print('')
bat = NonMarineMammal('Bat')
print(Dog.__mro__)
# output
Dog has 4 legs.
Dog can't swim.
Dog can't fly.
Dog is a warm-blooded animal.
Dog is an animal.
Bat can't swim.
Bat is a warm-blooded animal.
Bat is an animal.
(<class 'Dog'>,
<class 'NonMarineMammal'>,
<class 'NonWingedMammal'>,
<class 'Mammal'>,
<class 'Animal'>,
<class 'object'>)
So, super() can deal with multiple inheritance!!
And __mro__
(Method Resolution Order) tells you the order for parent methods to be called.
Thank you for reading!