Sitemap

Python Inheritance Explained With Examples

1 min readJul 6, 2023

--

In this tutorial, we’ll learn how to use Python inheritance. We’ll be uncovering the main concepts of inheritance in Python. We’ll see what its role is and how to properly use it.

Introduction: Python Inheritance

This concept is very beneficial in Python. By using this , we can reuse the existing code. Its superb to organize the code.

For instance, we’ve two classes. Class 1 and class 2. Class 2 is inheriting all the attributes and functions of class 1, so class 2 is a derived/child class. While class 1 is a parent/base class.

Get Zeeshan Ali’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s now understand inheritance in Python using practical code examples.

Syntax

Let’s first understand the syntax of how inheritance is implemented between Python classes.

class BaseClass:
class DerivedClass(BaseClass):
  • Using parenthesis after child class name and specifying the name of parent class will link these two classes as parent and child.
  • We can now easily reuse the attributes and methods of parent/base class using the new derived class.

Implementing Python Inheritance (Multiple Examples)

Below examples will practically demonstrate inheritance in Python in detail.

Example 1: Calling Method of Base Class Using Object of Child Class

class ClassA:
def parentFun(self):
print('Hye, How\'s Life')
class ClassB(ClassA):
def childFun(self):
print('Good')
obj=ClassB()
obj.childFun()
obj.parentFun()

We can see in the above code that object of class B has called the function of class A as well. It means attributes or methods in class A are now accessible by class B. This is how Python inheritance works. Continue reading…

--

--

Zeeshan Ali
Zeeshan Ali

Written by Zeeshan Ali

I am a Python developer and I am here to share what i have learnt so far. Hope my posts will help you in your python development journey. www.letmeflutter.com