Inheritance — Python

class DrinkMenu(Menu): makes a child class that inherits every attribute and method of Menu, its parent. A method with the same name in the child overrides…

Sweet tea with ice costs $2 more per glass. Toast never comes with ice. So drinks need one more attribute, iced, and a slightly different way to calculate the total. Everything else is exactly the same as in the Menu class from the previous lesson: the name, the price and how it prints. Do you need to write a new class from the beginning?

No. Mr. Darto doesn't design the drink card from the beginning either. He takes the old blank menu card (name, price) and adds one field: "with ice?". Everything on the menu card is still on the drink card. In Python this is called inheritance: a new class is made from an existing class. The blank menu card is the old class, and the blank drink card is the new class. The new class inherits (receives) every attribute and method of the old class, and then it may add some or replace some.

A child class

We use the Menu class from the previous lesson, then make DrinkMenu as its child:

class Menu:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def total(self, quantity):
        return self.price * quantity

    def __str__(self):
        return f"{self.name} ({self.price})"

class DrinkMenu(Menu):
    pass

tea = DrinkMenu("sweet tea", 5)
print(tea)            # sweet tea (5)
print(tea.total(4))   # 20

Adding and replacing methods

A child may write a method with the same name as one of its parent's methods. For the child's objects, that method replaces the parent's. This is called an override. At Mr. Darto's stall, a drink with ice costs $2 more per glass. This code also uses super(), which the next section explains:

class DrinkMenu(Menu):
    def __init__(self, name, price, iced=False):
        super().__init__(name, price)
        self.iced = iced

    def total(self, quantity):
        result = super().total(quantity)
        if self.iced:
            result = result + 2 * quantity
        return result

tea = DrinkMenu("sweet tea", 5, iced=True)
coffee = DrinkMenu("coffee with milk", 15)
toast = Menu("toast", 12)
print(tea.total(4))     # 28
print(coffee.total(3))  # 45
print(toast.total(2))   # 24
print(tea)              # sweet tea (5)
Call total of Calculation Result
tea.total(4) DrinkMenu 5 × 4 = 20, plus ice 2 × 4 = 8 28
coffee.total(3) DrinkMenu 15 × 3, iced is False 45
toast.total(2) Menu 12 × 2 24

super(): calling the parent's version

With super(), a child can call its parent's methods. The DrinkMenu class above uses it twice:

When a child has its own __init__, the parent's __init__ does not run automatically. Without the line super().__init__(name, price), the object tea never gets name and price:

Traceback (most recent call last):
  File "/home/darto/stall.py", line 17, in <module>
    print(tea.name)
          ^^^^^^^^
AttributeError: 'DrinkMenu' object has no attribute 'name'

So print(tea.name) gives an error, not sweet tea.

isinstance and the lookup order (MRO)

isinstance checks whether an object was made from a certain class. This code uses tea and toast from the example above:

print(isinstance(tea, DrinkMenu))    # True
print(isinstance(tea, Menu))         # True
print(isinstance(toast, DrinkMenu))  # False
print(type(tea) == Menu)             # False
print(DrinkMenu.__mro__)

The last line prints:

(<class '__main__.DrinkMenu'>, <class '__main__.Menu'>, <class 'object'>)

📌 More than one parent

A class may have several parents: class D(B, C):. In its MRO, the parents in the brackets are checked from left to right: B first, then C. A shared parent (A) is checked last, after all of its children:

class A:
    def hi(self):
        return "A"

class B(A):
    def hi(self):
        return "B"

class C(A):
    def hi(self):
        return "C"

class D(B, C):
    pass

print(D().hi())                          # B
print([k.__name__ for k in D.__mro__])   # ['D', 'B', 'C', 'A', 'object']

D has no hi, so Python looks in B first and stops there. The last line prints the name of each class in the MRO, in lookup order. Beginners rarely need this pattern. One parent is enough for almost every case.

⚠️ A super() call that's missing, or given the wrong arguments

TL;DR: class DrinkMenu(Menu): makes a child class that inherits every attribute and method of Menu, its parent. A method with the same name in the child overrides (replaces) the parent's, for the child's objects only. super() calls the parent's version: super().__init__(name, price) runs the parent's constructor (without self), and super().total(quantity) uses the parent's formula. A child's __init__ does not run the parent's automatically, so without super().__init__ you get an AttributeError. isinstance(tea, Menu) is True for children too, unlike type(tea) == Menu. Python looks for methods in the order of the MRO (the lookup order): the object's class first, then its parent, up to object.

⚡ A child inherits everything

Write:

class DrinkMenu(Menu):
    pass

tea = DrinkMenu("sweet tea", 5)
print(tea)            # sweet tea (5)
print(tea.total(4))   # 20

Meaning: DrinkMenu(Menu) means DrinkMenu is a child of Menu, the class from the previous lesson. Menu, written in the brackets, is called the parent class. The body of the child is empty (pass), but it already has __init__, total and __str__, all inherited from Menu.

⚡ Replace it, then call the parent's version

Write:

class DrinkMenu(Menu):
    def __init__(self, name, price, iced=False):
        super().__init__(name, price)
        self.iced = iced

    def total(self, quantity):
        result = super().total(quantity)
        if self.iced:
            result = result + 2 * quantity
        return result

Meaning: A method with the same name in the child overrides the parent's. super() calls the parent's method: super().__init__(name, price) fills in name and price, and super().total(quantity) uses the parent's formula. Then the child's total adds 2 per glass when iced is True. You don't send self, because super() already sends it.

⚡ A forgotten super()

Guess first: the line super().__init__(name, price) is deleted. What does print(tea.name) print?

Not sweet tea, but AttributeError: 'DrinkMenu' object has no attribute 'name'.

Meaning: When the child has its own __init__, the parent's __init__ doesn't run automatically. Call it through super().

⚡ A drink is still a menu item

Guess first: do isinstance(tea, Menu) and type(tea) == Menu give the same result?

No. isinstance gives True, because children count too. type(tea) == Menu gives False, because type only looks at the exact class.

Meaning: To check whether something is a Menu, use isinstance.

What you will learn