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 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 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__', 
'__subclasshook__']Code language: Python (python)

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?