Python 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, called inheritance. 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 basics from a Vehicle class. And, while we're at it, also define a Motorcycle class. Schematically, it looks like this:

Python class inheritance
Python class inheritance, ©

We've already seen inheritance at work. Remember how I told you 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 object:

>>> 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__', 

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. It reveals that object has an __init__ method. Cool, isn't it?

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 Vehicle class:

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("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.

If you liked this page, please share it with a fellow learner: