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()
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 ).
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.
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.
Use of super()Allows us to avoid using the base class name explicitly. Working with Multiple Inheritance.
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.
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!
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
).
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