Table of Contents
super() – basic functionality
- reference parent class ‚dynamically‘ instead of hard-coding it
- no need to call the name of the base class explicitly
- working with multiple inheritance
What super() can do: advantages
- simplyfies the use of your code by others
- may simply writing code by unnecessity of calling parent class explicitly
- less vulnerably to code changes
- for example when name of base class gets changed – super method in child class will still work without changes
super() with multiple inheritance (example)
class Animal:
def __init__(self, Animal):
print(Animal, '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, NonWingedMammal):
print(NonWingedMammal, "can't fly.")
super().__init__(NonWingedMammal)
class NonMarineMammal(Mammal):
def __init__(self, NonMarineMammal):
print(NonMarineMammal, "can't swim.")
super().__init__(NonMarineMammal)
class Dog(NonMarineMammal, NonWingedMammal):
def __init__(self):
print('Dog has 4 legs.');
super().__init__('Dog')
d = Dog()
print('')
bat = NonMarineMammal('Bat')
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.
Method Resolution Order (MRO)
- speficies in which order the related classed and objects are called
- called using: Class.__mro__
>>> Dog.__mro__
(<class 'Dog'>,
<class 'NonMarineMammal'>,
<class 'NonWingedMammal'>,
<class 'Mammal'>,
<class 'Animal'>,
<class 'object'>)
featured image by: @Quinoal (Twitter)
Neueste Kommentare