score:38
The purpose of super is to handle inheritance diamonds. If the class inheritance structure uses only single-inheritance, then using super() will result in the same calls as explicit calls to the "parent" class.
Consider this inheritance diamond:
class A(object):
def __init__(self):
print('Running A.__init__')
super(A,self).__init__()
class B(A):
def __init__(self):
print('Running B.__init__')
super(B,self).__init__()
class C(A):
def __init__(self):
print('Running C.__init__')
super(C,self).__init__()
class D(B,C):
def __init__(self):
print('Running D.__init__')
super(D,self).__init__()
foo = D()
which prints
Running D.__init__
Running B.__init__
Running C.__init__
Running A.__init__
while if we change B to B2 and use explicit calls to the parent __init__:
class B2(A):
def __init__(self):
print('Running B.__init__')
A.__init__(self)
class D2(B2,C):
def __init__(self):
print('Running D.__init__')
super(D2,self).__init__()
bar = D2()
then the chain of init calls becomes
Running D.__init__
Running B.__init__
Running A.__init__
So the call to C.__init__ is skipped entirely.
There is no one preferred option.
If you can guarantee that you do not want to support multiple inheritance then explicit parent calls are simpler and clearer.
If you wish to support multiple inheritance now or in the future, then you need to use super(). But understand that there are some pitfalls involved with using super, but with proper use these pitfalls can be avoided.
score:11
The primary purpose of super(Child, self).__init__() is allow initialization run properly in the case of multiple inheritance with diamond inheritance structures. If you explicitly call the base class constructors with multiple inheritance some initializers may be called twice. With single inheritance, there is no functional difference between using super and explicitly invoking the base class __init__() method. Note that because all python new-style classes subclass object, multiple inheritance always involves diamond inheritance.
super has a lesser benefit of reducing requires changes if you rename or change the base class.
In python 3, the arguments to super are optional, so you can just do super().__init__(). Python 2 still requires you to provide the arguments explicitly.
Credit To: stackoverflow.com
Related Query
- In multiple inheritance in Python, init of parent class A and B is done at the same time?
- When calling super().__init__ how can I tell if the super init is object.__init__ in python3?
- Beautifulsoup removing duplicated parent and child tags
- Get parent node?
- Importing BeautifulSoup from a (relative) parent folder, and a html parser alongside it
- How to inherit default values from Parent class using super()
- super in a metaclass
- How to find all `td` of `tr` parent tag which have `class="accordion-toggle main-row"' in BeautifulSoup?
- Check boolean field from parent model into lines - Odoo v8
- Override and extend method defined in parent class in Python
- can't set attribute in child class from parent
- Get first instance of text for parent item in BeautifulSoup
- Use of super in multi level inheritance
- Understanding multiple inheritence and super based on some code from David Beazly
- How to enable Swig to emit C++ super class
- Why stdin of parent process still accepts inputs after closing stdin file descriptor from a forked child process?
- python subclass autofilling parent method signature in IDE
- What is the purpose of using super in class initializer?
- Getting the parent attribute of an Excel xml with python lxml
- super and base class should have different instances of same attribute name
- Find parent sibling in mixed dict/list
- Creating a Qt child after adding its parent to a QGraphicsScene makes it immobile
- Python parent process is not catching SIGTERM/SIGINT signals when launching subprocess using os.sytem()
- Communication of a python parent process and a python subprocess
- XPath Get parent element from two children texts
- xpath - select parent where child has a specific attrib value with namespace dictionary
- Python lxml - can't get to parent
- Defining multiple parent xpath in the class method
- PyQt 5 QStandardItem Storing Old Parent
- Send data from C Parent to Python Child and back using a Pipe
- How do I override the init method in python list?
- How to ensure parent pipe is closed on parent crash in python multiprocessing?
- How to access variables from inherited class of parent in python?
- Subprocess call stopping asynchronously-executed Python parent process
- Impossible to add a background-image in parent QWidget with PyQt5?
- Create a subclass object with initialized parent object
- How to collect data from multiple threads in the parent process with ZeroMQ while keeping the solution both as simple & as scaleable as possible?
- custom warning handling class init error
- python multiple inheritance calling overridden functions in super context
- Typerror while accessing parent class data members
- PyQt4 QTableWidget: Set row width and column height to fill parent widget
- Sphinx ImportError for subdirectory import module from parent directory
- Create sub class by calling super class python
- Python: Inheriting methods of a parent class without being a child of the class
- Derived class doesn't recognise arguments of method from parent
- ndb allocate_ids with parent
- Getting an error saying super takes 1 argument but 0 given?
- Accessing parent class variable from an inner class?
- error when using method defined parent class
- Call a factory_boy super class method in a ~Factory sub-class without `self`
More Query from same tag
- Python 3.6 HTTP Server not reachable when compiled by PyInstaller on Windows
- "Urlopen error unknown url type" when running Python script from CMD
- python beautifulsoup - how to go to next page while next page doesn't have an unique address
- Python : Appending Integer array in list while iterating
- How to overwrite label in tkinter, after running another functions
- A random list of four items, but with no duplicates
- matplotlib figure does not continue program flow after close event triggered inside tk app
- Is there a way to distribute lots to sub set of lists using a predefined steeper?
- Python XOR operation and ser.read()
- PyInstaller works for Linux on Windows, but I can't get it to work with Windows to create a .exe
- How Can I activate virtual environment in wsl in pycharm while using debug mode of a script (Linux machine)
- Get all images of a multi-frame DICOM file
- How to set X-Axis values as dates in matplotlib?
- how can I get the searched string from list in my es.search result?
- Reading and processing large text file in batches using islice and multiprocessing
- Run Python CGI Script on Windows XP
- Export data from python to csv
- Identify source widget when multiple widgets share the same callback
- unable to acces taskid of Celery task in helper fucntion of the same task?
- including python package dependecy as an executable
- Find element by name using wildcard?
- Weird characters after changing to UTF-8 in Python
- Scrape website data for CSV
- Adding a function in this timed input
- How to hide or solve Tensorflow warning about TF_FORCE_GPU_ALLOW_GROWTH?
- Registration timeout on PBS cluster with Ipython parallel
- Python: Strange hanging behavior when piping large stdout of a subprocess
- How to generalize the Australian shuffle?
- how to show an image after pca?
- How to inherit default values from Parent class using super()
- Module requests Python
- Calling overloaded method using super() yields AttributeError
- If number is a multiple of n - Python
- Triangle angle classification
- Fill in Ansible template on a Windows system