Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's super() function

In the below sample, the last 2 lines in the B.Go() method both call the Go() method from class A. Are they functionally identical? Is the only benefit to using super() that I don't have to know the inherited class name?

class A(object):
    def Go(self):
        print "Calling A.Go()"

class B(A):
    def Go(self):
        super(B, self).Go()
        A.Go(self)

inst = B()
inst.Go()
like image 853
tMC Avatar asked Jun 14 '11 23:06

tMC


People also ask

Is super () necessary Python?

In general it is necessary. And it's often necessary for it to be the first call in your init. It first calls the init function of the parent class ( dict ).

What is super () is used for?

The super keyword refers to superclass (parent) objects. It is used to call superclass methods, and to access the superclass constructor. The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.

What is super () __ Init__ in Python?

The “__init__” is a reserved method in python classes. It is known as a constructor in Object-Oriented terminology. This method when called, allows the class to initialize the attributes of the class. Python super() The super() function allows us to avoid using the base class name explicitly.

Why do we need super () in an extended class Python?

Use of super()Allows us to avoid using the base class name explicitly. Working with Multiple Inheritance.


3 Answers

No, super() does something a direct call to A.Go can't. super(B, self).Go() calls the next method in the method resolution order. It calls the method that would have been called had B not implemented the method at all. In direct linear inheritance this is always A, so there is no real difference (besides the class you repeat.) In the case of multiple inheritance, however, the next class in the normal method resolution order is not necessarily the direct baseclass of the current class. See the explanation for diamond inheritance in Guido's original explanation of these features.

like image 106
Thomas Wouters Avatar answered Sep 17 '22 14:09

Thomas Wouters


In addition to the excellent answer provided by Thomas Wouters, I'd add that super() is additionally very useful because it is a computed indirection. One key benfit of using super() is that you don't have to specify the delegate class by name, which makes it easy to change the base class later. Raymond Hettinger has a great post on about this: Python's super() considered super!

like image 30
zeekay Avatar answered Sep 21 '22 14:09

zeekay


Not exactly. By using super you need only instantiate B, there is one instance. The second line makes a new instance of A, may possibly have side effects in the initializer, and doesn't share other instance attribute or state (of B instance inst).

like image 22
Keith Avatar answered Sep 19 '22 14:09

Keith