Inheritance in Python

Coding with Python

🕑 This lesson will take about 15 minutes

In object-oriented programming, inheritance is the idea that when a class of objects is defined, any sub-class that is defined can inherit the definitions of one or more general classes. A sub-class is a class that “inherits” properties and methods from an existing class and can have additional properties and methods of its own too.

  • To the programmer, this means that an object in a sub-class does not need to carry its own definition of data and methods that are generic to the main class (or classes) of which it is a part.

  • This speeds up program development by reducing repetition in code and also ensures an inherent validity to the defined subclass object (what works and is consistent about the class will also work for the subclass).

  • Classes can be defined as sub-classes that extend a parent class. This means that ‘child’ or ‘sub’ classes can inherit all the attributes and methods of the parent class (without needing to write any code), while allowing further specialised additions to be coded.

  • This results in substantial time savings.

Example

Let’s say you want to create a program that stores information about people in a school such as teachers, admin staff, and students. You could create a general Person class that just defines properties and behaviours that will be common to all people (such as first name, last name and date of birth). You can then create sub-classes (eg. Teacher, Student, Admin, etc.) which inherit those properties as well as behaviours from the Person class whilst also specifying additional properties and behaviours relevant only to each sub-class (eg. there might be a faculty property for teachers and a yearGroup property for students). Thanks to inheritance, you don’t have to write the code that defines properties such as first name, last name, and date of birth for every sub-class as they have already been defined in the Person class and can be inherited into those sub-classes. This will save you time and the amount of code you need in your program.

In the example code below, there is a Person class and then there also two sub-classes (Student and Teacher) that inherit properties/attributes and behaviours/methods from the Person class.

In the next lesson, we will look at static methods and class methods.

Next lesson: Static methods and class methods