Sitemap
Gaurav Verma

Gaurav Verma

Member-only story

Inheritance in Python

4 min readSep 8, 2024
Press enter or click to view image in full size

Inheritance is a mechanism that allows a derived (child) class to inherit properties and methods from a base (parent) class.
Python Inheritance Syntax is

class BaseClass:
#Body of class

class DerivedClass(BaseClass):
#Body of class
class BaseClass:
def base_fun(self):
print("I am Base class function")

class ChildClass(BaseClass):
def child_fun(self):
print("I am Child class function")

obj = ChildClass()
obj.base_fun() #Child class can access base class function
obj.child_fun()

Constructor behaviour in Inheritance

if no constructor (__init__() method) is provided in a child class, the constructor of the base (parent) class is automatically called when an object of the child class is created. This is because Python will inherit the __init__() method from the parent class if it is not explicitly overridden in the child class.
If the child class has its own constructor, you can call the base class constructor explicitly using either the class name or super(). Here is example to demonstrate:

Example when no constructor in child class

class BaseClass:
def __init__(self, instance_var1):
self.instance_var1 = instance_var1
print("Instance variable value is "…

--

--