Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Python super() with __init__() methods [duplicate]

I'm trying to understand the use of super(). From the looks of it, both child classes can be created, just fine.

I'm curious to know about the actual difference between the following 2 child classes.

class Base(object):     def __init__(self):         print "Base created"  class ChildA(Base):     def __init__(self):         Base.__init__(self)  class ChildB(Base):     def __init__(self):         super(ChildB, self).__init__()  ChildA()  ChildB() 
like image 992
Mizipzor Avatar asked Feb 23 '09 00:02

Mizipzor


People also ask

What does super () __ Init__ do 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. The super() function allows us to avoid using the base class name explicitly.

What is __ Super __ in Python?

An Overview of Python's super() Function While the official documentation is fairly technical, at a high level super() gives you access to methods in a superclass from the subclass that inherits from it. super() alone returns a temporary object of the superclass that then allows you to call that superclass's methods.

How does super () work in Python?

The super() function in Python makes class inheritance more manageable and extensible. The function returns a temporary object that allows reference to a parent class by the keyword super. The super() function has two major use cases: To avoid the usage of the super (parent) class explicitly.

What is __ Init_subclass __ in Python?

__init_subclass__(cls) method is called on a given class each time a subclass cls for that class is created. Syntax. Minimal Example. Class Hierarchy with __init_subclass__()


1 Answers

super() lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven't already.

Note that the syntax changed in Python 3.0: you can just say super().__init__() instead of super(ChildB, self).__init__() which IMO is quite a bit nicer. The standard docs also refer to a guide to using super() which is quite explanatory.

like image 128
Kiv Avatar answered Oct 16 '22 08:10

Kiv