简体   繁体   中英

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.

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM