Snerd
Snerd

Reputation: 1553

Python super() inheritance and needed arguments

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.

Upvotes: 18

Views: 6812

Answers (2)

Abin Thomas
Abin Thomas

Reputation: 101

You don't have to pass the child instance as an argument from python3 onwards if I'm not mistaken. Plus for an in-depth understanding of the super() method refer to https://rhettinger.wordpress.com/2011/05/26/super-considered-super/

Upvotes: 0

lvc
lvc

Reputation: 35059

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).

Upvotes: 25

Related Questions