I sort of understand that...
You have had two attempts at this, neither correct:
- "will call both the parent's class method and the child's class method" - no, it calls the method on the next class in the MRO (Method Resolution Order); and
- "is to prevent the overriding of the the base's class method when a
ChildClass
has the same method" - no, the child class implementation does override the base class, super
allows you to access inherited implementations without explicitly specifying a class.
What is the practical use of this?
At the very simplest, imagine that we have a base class with one initialisation parameter:
def Base(object):
def __init__(self, attr1):
self.attr1 = attr1
and a child class with two. Then we can implement the child in one of two ways, either without calling the base class:
def Child(Base):
def __init__(self, attr1, attr2):
self.attr1 = attr1
self.attr2 = attr2
or by calling the base class:
def Child(Base):
def __init__(self, attr1, attr2):
super(Child, self).__init__(attr1)
self.attr2 = attr2
Note that this reduces repetition, and if we change the handling of attr1
in the Base
class (e.g. we assign the parameter to a "private" attribute _attr1
and access it via a @property
) we only have to make that change once.
You could also implement the second as:
def __init__(self, attr1, attr2):
Base.__init__(self, attr1)
self.attr2 = attr2
but this again means repetition - we've now had to specify the name Base
in two places in Child
, so if we rename the Base
or change the inheritance for Child
we have to make alterations in two places.