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









