I am currently down the rabbit hole trying to understand metaclasses and as such went back to refresh my understanding of super() and type.
While refreshing I came across a geeksforgeeks super() article and it had a rather weird example.
here is the example
class Animals:
# Initializing constructor
def __init__(self):
self.legs = 4
self.domestic = True
self.tail = True
self.mammals = True
def isMammal(self):
if self.mammals:
print("It is a mammal.")
def isDomestic(self):
if self.domestic:
print("It is a domestic animal.")
class Dogs(Animals):
def __init__(self):
super().__init__()
def isMammal(self):
super().isMammal() <- Why do this?
I understand that when inheriting from a parent class, the functions like __init__
must be called to be initialized, hence the super().__init__()
but why do this also in the function? I thought that functions were inherited. Is this so that we can run the parent function along with modifications?
Why not call a parent function, within a new function?
def mammal_can_dance(self):
self.isMammal()
print("and can dance")
Yes. In this case, since neither the overloading __init__
nor isMammal
do anything (besides calling their parent implementations), they could just be omitted for the same result:
class Dogs(Animals):
pass
Here the parent methods would simply be inherited and do exactly the same thing.
But if you want to use the parent's implementation and add something to it, you'd use super
and do something in addition:
class Foo(Bar):
def baz(self):
some_list = super().baz()
return some_list + ['quux']