Object-oriented programming
Inheritance
Suppose the pizza shop starts selling gluten-free pizzas. They behave almost exactly like regular pizzas, with a few differences. You could copy the whole Pizza class and edit the copy, or you could say: a gluten-free pizza is a pizza, plus a few changes. That second idea is called inheritance.
1Reusing a class
Inheritance lets a new class start from an existing class and take over everything in it. The existing class is called the superclass, also known as the parent or base class. The new class is the subclass, also known as the child or derived class. A subclass inherits all the attributes and methods of its superclass.
You write the superclass name in parentheses after the subclass name. Here is the Pizza class from earlier chapters, and a subclass that adds nothing yet. The word pass is a placeholder for an empty body.
The class GlutenFreePizza contains no code of its own, yet its objects can be created with the same arguments, print themselves, and add toppings. All of that was inherited from Pizza.
Inheritance is useful for three reasons.
- Reuse. The shared code is written once, in the parent.
- Maintenance. A fix or change in the parent reaches every child automatically.
- Customization. Each child adds or changes only what makes it different.
2The is-a test
Inheritance should be used only when the child really is a kind of the parent. Say the sentence aloud. If it sounds right, inheritance fits.
| Sentence | Sounds right? | What to do |
|---|---|---|
| A gluten-free pizza is a pizza. | Yes | Inherit: class GlutenFreePizza(Pizza) |
| A pizza has toppings. | It "has", not "is" | Use an attribute: self.toppings |
| A pizza is an oven. | No | No relationship |
Python can also check the relationship for you. The function isinstance(obj, Class) asks whether an object is an instance of a class or of any class that inherits from it. The function issubclass(Child, Parent) compares two classes.
A gluten-free pizza counts as a Pizza, but a plain pizza does not count as a GlutenFreePizza. The relationship runs in one direction only.
3Adding to a subclass
A subclass can have methods that its parent does not. Inside them, self still gives access to everything inherited, such as self.size.
The method label uses the inherited attribute self.size, and add_topping works because it was inherited. The last line shows that additions do not travel upward: a plain Pizza does not have label. Inheritance only passes things from the parent down to its children.
4Overriding a method
If a subclass defines a method with the same name as one in its parent, the subclass version is used for objects of the subclass. This is called method overriding. Predict what each of the two lines prints.
Show the answer
The first line is large pizza, $16, toppings: ['basil'] and the second is gluten-free large pizza, $16, toppings: ['basil']. Python looks for __str__ in the object's own class first. A GlutenFreePizza has one, so that version runs. A plain Pizza uses its own. Overriding the method in the child does not change the parent.
The same call, print(...), runs different code depending on the kind of object. That is a useful property, and programmers have a name for it: polymorphism.
5Calling the parent with super()
The overriding method above repeated the parent's text. Usually you want to keep the parent's version and add to it. The function super() gives you the parent's version of a method, so you can call it from the child.
The child adds its own words and lets the parent do the rest. If the parent's text ever changes, the child follows automatically.
super() in the constructor
The most common place to use super() is the constructor. Say a gluten-free pizza costs 2 more and records the flour it uses. The child's __init__ calls the parent's __init__ first, so the parent still sets up size, toppings, and price. Then the child adds its own work.
The price is 18: the large base of 15, plus 1 for the basil, which the parent added, plus 2 from the child.
Show the fix
The pizza has a flour but no size, because Pizza.__init__ never ran. Add super().__init__(size, toppings) as the first line of the child's constructor.
You will often see this pattern written with *args and **kwargs, as in the Args and Kwargs chapter. The child does not need to know what the parent's constructor expects. It passes everything along.
6Kinds of inheritance
Classes can be connected in several shapes. Here are five names, with the ones you can build from the classes in this chapter.
| Kind | Shape | Pizza example |
|---|---|---|
| Single | One child, one parent | GlutenFreePizza(Pizza) |
| Multilevel | A chain: a child whose parent has its own parent | DeepStuffedPizza(StuffedPizza), where StuffedPizza(Pizza) |
| Hierarchical | Several children share one parent | StuffedPizza(Pizza) and GlutenFreePizza(Pizza) |
| Multiple | One child, several parents | Written class C(A, B). Not built here. |
| Hybrid | A mix of two or more of the above | Not built here. |
The next cell builds a hierarchy that is both hierarchical and multilevel. To keep it short, each class has one small method.
The loop calls the same method on four kinds of object, and each one answers in its own way. The last line shows that a grandchild is still a kind of its grandparent.
7Practice
Exercise 1: a stuffed pizza
Write the constructor of StuffedPizza. It takes size, toppings, and stuffing. Let the parent set up the usual attributes, store the stuffing, and add 2 to the price.
Hint
Start with super().__init__(size, toppings) so the parent creates size, toppings, and price. After that line, store stuffing on self and add 2 to self.price.
Show a solution
def __init__(self, size, toppings, stuffing):
super().__init__(size, toppings)
self.stuffing = stuffing
self.price += 2
Exercise 2: override and extend
Finish the __str__ method of GlutenFreePizza. It should return the parent's text with the words gluten-free in front. Do not copy the parent's code.
Hint
Call the parent's version with super().__str__() and put "gluten-free " in front of what it returns. The method must return the text, not print it.
Show a solution
def __str__(self):
return "gluten-free " + super().__str__()