Considering:
class Parent(object):
def altered(self):
print "PARENT altered()"
class Child(Parent):
def altered(self):
print "CHILD, BEFORE PARENT altered()"
super(Child, self).altered() # what are the arguments needed? Why Child and self?
print "CHILD, AFTER PARENT altered()"
In Python 2.7, Why must Child
be passed as an argument to the super()
call? What are the exact intricacies of using super instead of just letting it work.
The method being called upon by super() must exist. Both the caller and callee functions need to have a matching argument signature. Every occurrence of the method must include super() after you use it.
super() does not accept any arguments. One core feature of object-oriented programming languages like Python is inheritance. Inheritance is when a new class uses code from another class to create the new class.
The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.
In a class hierarchy with single inheritance, super helps to refer to the parent classes without naming them explicitly, thus making the code more maintainable. Here, with the help of super(). f1(), the f1() method of the super class of Child class i.e Parent class has been called without explicitly naming it.
super
figures out which is the next class in the Method Resolution Order. The two arguments you pass in are what lets it figure that out - self
gives it the entire MRO via an attribute; the current class tells it where you are along the MRO right now. So what super is actually doing is basically:
def super(cls, inst):
mro = inst.__class__.mro() # Always the most derived class
return mro[mro.index(cls) + 1]
The reason it is the current class rather than the base class is because the entire point of having super is to have a function that works out what that base class is rather than having to refer to it explicitly - which can cause problems if the base class' name changes, if you don't know exactly what the parent class is called (think of factory functions like namedtuple
that spit out a new class), and especially in multi-inheritance situations (where the next class in the MRO mightn't be one of the current class' bases).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With