How can I organize my Python code to make it easier to change the base class?


Before learning how to change the base class, let us first understand the concept of base and derived class in Python.

We will learn about Base and Derived class using the concept of Inheritance. In multiple inheritance, the features of all the base classes are inherited into the derived class. Let us see the syntax −

Syntax

Class Base1: Body of the class Class Base2: Body of the class Class Base3: Body of the class . . . Class BaseN: Body of the class Class Derived(Base1, Base2, Base3,, BaseN): Body of the class

The Derived class inherits from both Base1, Base2 and Base3classes.

In the below example, Bird class inherits the Animal class.

  • Animal is the parent class also known as super class or base class.
  • Bird is the child class also known as sub class or derived class.

Example

The issubclass method ensures that Bird is a subclass of Animal class.

class Animal: def eat(self): print("It eats insects.") def sleep(self): print("It sleeps in the night.") class Bird(Animal): def fly(self): print("It flies in the sky.") def sing(self): print("It sings a song.") print(issubclass(Bird, Animal)) Koyal= Bird() print(isinstance(Koyal, Bird)) Koyal.eat() Koyal.sleep() Koyal.fly() Koyal.sing()

Output

True
It eats insects.
It sleeps in the night.
It flies in the sky.
It sings a song.
True

To make it easier to change the base class, you need to assign the base class to an alias and derive from the alias. After that, change the value assigned to the alias.

The above step also works if you want to decide which base class to use. For example, let’s see the code snippet displaying the same −

class Base: ... BaseAlias = Base class Derived(BaseAlias):

Updated on: 19-Sep-2022

251 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements