Trusted answers to developer questions

What is class inheritance in Python?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

Inheritance is a way by which a subclass can inherit the attributes and methods of another class. The new class is called derived (or child) class and the one from which it inherits is called the base (or parent) class.

Types of Inheritance

There are three types of inheritance in Python:

Single inheritance

In single inheritance, the derived class is derived from only one base class.

The general syntax for single class inheritance is:


class BaseClass:
  Base class body
class DerivedClass(BaseClass):
  Derived class body
svg viewer

Multiple Inheritance

In multiple inheritance, the derived class is derived from more than one base class.

The general syntax for multiple class inheritance is:

class BaseClass1:
  Base class1 body
class BaseClass:
  Base class2 body
class DerivedClass(BaseClass1,BaseClass2):
  Derived class body
svg viewer

Multilevel Inheritance

In multilevel inheritance, the derived class is derived from another derived class.

The general syntax for multilevel class inheritance is:


class Base:
    Base Class body
class Derived1(Base):
    Derived Class1 body
class Derived2(Derived1):
    Derived Class2 body 
svg viewer

Benefits of Class Inheritance

Here are a few main advantages of using Inheritance:

Reusability of code

Since the derived class inherits features from the base class, adding new features to it. This results in re-usability of code. This makes the code more scalable.

Structured Code

By dividing the code into classes, we can structure our software better by dividing functionality into classes.

RELATED TAGS

python
inheritance
class
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?