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
class DrinkMenu(Menu):meansDrinkMenuis a child ofMenu. The class in the brackets is called the parent (parent class or superclass). The new class is called the child (child class or subclass).passmeans the class body is empty. Even when it is empty,DrinkMenualready has__init__,totaland__str__. All of them are inherited fromMenu.DrinkMenu("sweet tea", 5)runs the__init__ofMenu, because the child has no__init__of its own.
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 |
- The child's
__init__takes one extra parameter,iced, with the default valueFalse.coffeeis made without sendingiced, soicedisFalseand nothing is added to its price. totalin the child overridestotalin the parent, but only forDrinkMenuobjects.toastis a plainMenuobject, so it still uses thetotalofMenu.__str__is not written again, soprint(tea)still uses the one inherited fromMenu.
super(): calling the parent's version
With super(), a child can call its parent's methods. The DrinkMenu class above uses it twice:
super().__init__(name, price)runs the__init__ofMenu, which fills inself.nameandself.price. Only after that does the child addself.iced. Note that you do not sendself, becausesuper()already sends it.super().total(quantity)calls thetotalofMenuto get the base price. So the formulaself.price * quantityis not written 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'>)
isinstance(obj, Class)isTruewhenobjwas made from that class or a child of it. A drink is still a menu item.type(tea) == MenuisFalse, becausetypeonly looks at the exact class. To check whether something is aMenu, useisinstance.__mro__(method resolution order) is the order in which Python looks for attributes and methods. The order is: the object's own class first, then its parent, and so on up toobject, the parent of every class. Python uses the first one it finds.- That lookup order is how an override works.
tea.totalis already found inDrinkMenu, so thetotalofMenuis not used.__str__is not inDrinkMenu, so Python moves up toMenu. objectis also where the default__str__comes from. That default__str__is the one that prints<__main__.Menu object at 0x...>when your class has no__str__of its own.
📌 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
- Forgetting
super().__init__(...). The child's__init__replaces the parent's, so the parent's attributes are never made:AttributeError: 'DrinkMenu' object has no attribute 'name'. - Sending
selftosuper()as well.super().__init__(self, name, price)is refused:TypeError: Menu.__init__() takes 3 positional arguments but 4 were given.super()already sendsself. - Too few arguments to
super().__init__.super().__init__(name)fails:TypeError: Menu.__init__() missing 1 required positional argument: 'price'. - Inheriting for a "has a" link. Use inheritance when the child is a parent: a drink is a menu item. An
Orderhas many menu items, but an order is not a menu item. So keep the items as an attribute, and do not writeclass Order(Menu).
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.