Today, you’ll focus on inheritance in OOP. This text is a continuation of the article by David Amos you started on Day 1.
How Do You Inherit From Another Class in Python?
Inheritance is the process by which one class takes on the attributes and methods of another. Newly formed classes are called child classes, and the classes that you derive child classes from are called parent classes.
You inherit from a parent class by creating a new class and putting the name of the parent class into parentheses:
inheritance.py
class Parent:
hair_color = "brown"
class Child(Parent):
pass
In this minimal example, the child class Child
inherits from the parent class Parent
. Because child classes take on the attributes and methods of parent classes, Child.hair_color
is also "brown"
without your explicitly defining that.
Child classes can override or extend the attributes and methods of parent classes. In other words, child classes inherit all of the parent’s attributes and methods but can also specify attributes and methods that are unique to themselves.
Although the analogy isn’t perfect, you can think of object inheritance sort of like genetic inheritance.
You may have inherited your hair color from your parents. It’s an attribute that you were born with. But maybe you decide to color your hair purple. Assuming that your parents don’t have purple hair, you’ve just overridden the hair color attribute that you inherited from your parents:
inheritance.py
class Parent:
hair_color = "brown"
class Child(Parent):
hair_color = "purple"
If you change the code example like this, then Child.hair_color
will be "purple"
.
You also inherit, in a sense, your language from your parents. If your parents speak English, then you’ll also speak English. Now imagine you decide to learn a second language, like German. In this case, you’ve extended your attributes because you’ve added an attribute that your parents don’t have:
inheritance.py
class Parent:
speaks = ["English"]
class Child(Parent):
def __init__(self):
super().__init__()
self.speaks.append("German")
You’ll learn more about how the code above works in the sections below. But before you dive deeper into inheritance in Python, you’ll take a walk to a dog park to better understand why you might want to use inheritance in your own code.
Example: Dog Park
Pretend for a moment that you’re at a dog park. There are many dogs of different breeds at the park, all engaging in various dog behaviors.
Suppose now that you want to model the dog park with Python classes. The Dog
class that you wrote in the previous section can distinguish dogs by name and age but not by breed.
You could modify the Dog
class in the editor window by adding a .breed
attribute: