strongrest.blogg.se

Super in oop python
Super in oop python












super in oop python
  1. #SUPER IN OOP PYTHON HOW TO#
  2. #SUPER IN OOP PYTHON PORTABLE#

The goal was to provide a much more abstract and portable solution for initializing classes. To make this process easier, Python’s core development team created the super function. We can see that there’s a base or parent class (also sometimes called the super class), and a denoted subclass.īut we still need to initialize the parent class within the subclass.

super in oop python

The initial code will look something like this: class MyParentClass(object):Īs you can see, this is a setup commonly used for single inheritance.

#SUPER IN OOP PYTHON HOW TO#

How to Call Super in Python 2 and Python 3?įirst, we’ll take a regular class definition and modify it by adding the super function. Whereas the normal way to call super (in older builds of Python) is: super(subClass, instance).method(args)Īs you can see, the newer version of Python makes the syntax a little simpler. In Python 3 and above, the syntax for super is: super().methoName(args) So, for all intents and purposes, super is a shortcut to access a base class without having to know its type or name. The super function handles all of it for you. Plus, there’s no need to know the details about the base class that’s being used as an extender. The great thing about super is that it can be used to enhance any module method. But it’s important to remember that Python has evolved considerably since 2.2 and many of these concerns no longer apply. It even garnered a reputation for being harmful. Many developers found the documentation unclear, and the function itself to be tricky to implement. When the super function was introduced it sparked a bit of controversy. This use is considered exclusive to Python, because it’s not possible with languages that only support single inheritance or are statically compiled. Use Case 2: Super can be called upon in a dynamic execution environment for multiple or collaborative inheritance. It’s somewhat of a shortcut, but more importantly, it helps keep your code maintainable for the foreseeable future. Use Case 1: Super can be called upon in a single inheritance, in order to refer to the parent class or multiple classes without explicitly naming them. The super function is somewhat versatile, and can be used in a couple of ways. The search order is same as that used by getattr() except that the type itself is skipped.” How Is the Super Function Used? This is useful for accessing inherited methods that have been overridden in a class. “ return a proxy object that delegates method calls to a parent or sibling class of type.

super in oop python

Or, as the official Python documentation says:














Super in oop python