Python

Inheritance

Inheritance is one of the key concepts of object orientated programming (OOP). Objects are created using classes, but that’s not all.

A class can inherit the methods and variables from another class. This principle helps us to avoid duplicate code. In turn, a created object has methods and variables from both classes.

Related course: Python Beyond the Basics – Object-Oriented Programming

Inheritance example

We start by defining a class A which has a method A.

class A:
def A(self):
print('A')

Then we create class B and let it inherit from class A.

class B(A):
def B(self):
print('B')

If you create an object from class B, it has both the methods defined in class A and class B.

Full inheritance code:

class A:
def A(self):
print('A')

class B(A):
def B(self):
print('B')

o = B()
o.A()
o.B()

Previous Post Next Post

Cookie policy | Privacy policy | ©

OOP