liveBook · Manning

Superclass

As explained in Practices of the Python Pro

A superclass is a class from which another class derives structure and behavior through inheritance.

A superclass is a class whose structure and behavior another class inherits. The inheriting class, called a subclass, can specialize or override that behavior. Inheritance expresses an “is-a” relationship: a CarbonFiberFrame is a Frame, while a Bicycle has a Tire through composition. section 8.1.2 section 8.2.1

Inheritance is most useful for specializing behavior, not merely reusing code. A healthy hierarchy is shallow and narrow, with subclasses at the leaves and each subclass using the behavior of its superclass. Deep or wide hierarchies make relationships harder to reason about and can spread unintended changes. section 8.2.3 section 8.1.2

Specializing superclass behavior

class Bird: def fly(self): print('flying!') class Hummingbird(Bird): def fly(self): print('zzzzzooommm!') class Penguin(Bird): def fly(self): print('no can do.') Use super() when an override must retain the superclass behavior while adding specialization. For example, CorruptTeller.deposit records a fee and then calls super().deposit(amount * 0.99, account). Keep method signatures compatible so subclass instances remain substitutable for superclass instances. section 8.2.3 section 8.3.2 section 8.2.2

Listing 8.2. Using super() to access superclass behavior
class Teller:
    def deposit(self, amount, account):
        account.deposit(amount)
class CorruptTeller(Teller):                     #1
    def __init__(self):
        self.coffers = 0

    def deposit(self, amount, account):          #2
        self.coffers += amount * 0.01            #3
        super().deposit(amount * 0.99, account)  #4

Inspect the Python listing to see an override preserve superclass behavior through super(). section 8.3.2

How Practices of the Python Pro covers it

How deep it goes
Explains inheritance, hierarchy shape, superclass access, and substitutability, but stops short of detailed multiple-inheritance mechanics.
Examples
Demonstrates Bird subclasses, CarbonFiberFrame and Frame, and a Teller override using super().
What it assumes
Explains superclass and subclass terminology directly while assuming familiarity with classes, methods, and object-oriented relationships.
What you can do after
Apply it via Python inheritance and super() while checking hierarchy size, behavior specialization, and substitutability.
How it connects
Connects superclasses with subclasses, inheritance, composition, specialization, interfaces, and substitutability.

Also explained in

Compare how 10 books explain superclass →

Related concepts

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