What is inheritance?
In programming, it’s considered good style to reuse as much code as possible. There’s even a nice acronym for this practice, called DRY: Don’t Repeat Yourself. Classes help you to avoid repeating code because you can write a class once and create many objects based on it. However, they also help you in another way when using Python inheritance.
Inheritance in Python
We’ve already seen inheritance at work, but you may not have realized it yet. Remember how I told you about Python constructors and that every class has a constructor (
__init__), even when you don’t define one? It’s because every class inherits from the most basic class in Python, called
>>> dir(object) ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
When I told you ‘everything in Python is an object’, I really meant everything. That includes classes and as you can see we can use
dir() on a class too; the
object class. It reveals that
object has an
__init__ method. Cool, isn’t it?
Python inheritance example
Classes can inherit properties and functions from other classes, so you don’t have to repeat yourself. Say, for example, we want our Car class to inherit some more generic functions and variables from a Vehicle class. While we’re at it, let’s also define a Motorcycle class. Schematically, it looks like this:
Inheritance maps to many real-life situations. Let’s see inheritance in action, based on the class diagram above. We’ll start with a generic
class Vehicle: def __init__(self, started = False, speed = 0): self.started = started self.speed = speed def start(self): self.started = True print("Started, let's ride!") def stop(self): self.speed = 0 def increase_speed(self, delta): if self.started: self.speed = self.speed + delta print("Vrooooom!") else: print("You need to start me first")
Now we can redefine our Car class, using inheritance:
class Car(Vehicle): trunk_open = False def open_trunk(self): trunk_open = True def close_trunk(self): trunk_open = False
Our car inherits all methods and variables from the Vehicle class but adds an extra variable and two methods to operate the trunk.