Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 937
Snerd Avatar asked Apr 09 '13 07:04

Snerd


People also ask

Does super need arguments Python?

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.

What arguments does super take Python?

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.

What is the use the super () function in Python inheritance?

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.

How does super () method play an important role in inheritance?

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.


1 Answers

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

like image 80
lvc Avatar answered Nov 15 '22 19:11

lvc