liveBook · Manning

Super keyword

As explained in Python How-To

The super construct accesses or invokes inherited methods, constructors, or attributes according to a language’s inheritance rules.

When an override needs to keep a superclass’s behavior, call super() instead of replacing that behavior entirely. In a Supervisor.logout method, super().logout() runs the inherited logout implementation before additional supervisor-specific actions. super() also provides access to a superclass constructor when customized initialization is needed. section 8.5.3 section 8.5.6

class Supervisor(Employee):
   def logout(self):
       super().logout()
       print("Additional logout actions for a supervisor")

See the override that calls the superclass logout method before adding a supervisor-specific action. section 8.5.3

Listing 10.10 Creating a custom class for sorting poker cards
class PokerOrder(int):
   def __new__(cls, x):
       numbers_mapping = {'J': 11, 'Q': 12, 'K': 13, 'A': 14}
       casted_number = numbers_mapping.get(x, x)
       return super().__new__(PokerOrder, casted_number)

This PokerOrder example uses super().__new__ to construct an int subclass with mapped values for face cards. section 10.5.3

Method resolution order (MRO) determines where Python finds a method or attribute in an inheritance hierarchy. Inspect a class’s MRO when reasoning about which implementation is reached; the basic explanation focuses on a subclass with one superclass. section 8.5.3

How Python How-To covers it

How deep it goes
Explains super() as a proxy and demonstrates method and constructor calls; limits its MRO discussion to single inheritance.
Examples
Uses a Supervisor logout override and a PokerOrder int subclass that maps face cards for sorting.
What it assumes
Assumes familiarity with classes, inheritance, method overriding, and __init__.
What you can do after
Apply super() to reuse a superclass implementation while customizing a subclass method or constructor.
How it connects
Connects super() to inheritance, method overriding, method resolution order, and constructors.

Also explained in

Compare how 6 books explain super keyword →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.