How to implement class inheritance in Python?

Class inheritance allows us to create a new class based on the already existing class. The already existing class is known as the base or parent class, and the new class is called the child or derived class.

The derived or child class inherits the attributes and methods of the base or parent class. The inheritance structure looks like the following:

class parentClass:
# Class-level attributes
def __init__(self, parameters):
# Constructor method
def methods(self, parameters):
# Method definition
# Inherits parentClass
class childClass(parentClass):
pass

We can use the functions of the parent class by creating an object for the child class. The following shows the object creation of the child class.

class parentClass:
# Class-level attributes
def __init__(self, parameters):
# Constructor method
def parent_methods(self, parameters):
# Method definition
# Inherits parentClass
class childClass(parentClass):
pass
object_child = childClass(arguments)
object_child.paremt_methods(arguments)

The object_child can use the parent_methods() of the parentClass because the childClass is derived from it.

Example

The following is an executable example of a class inheritance method:

# Create a class "Person"
class Person:
# function to initialize the name and age
def __init__(self, name, age):
self.name = name
self.age = age
# class function to determine if a person is adult or not
def adult(self, name, age):
if age>=18:
print(name, "is an adult.")
else:
print(name, "is not an adult.")
class Student(Person):
pass
print("Parent class object: ")
# crearting a new object for Person class
obj1 = Person("Parent", 22)
# Class constructor and function call
print(obj1.name)
print(obj1.age)
obj1.adult(obj1.name, obj1.age)
print("Child class object: ")
# crearting a new object for Student class
obj2 = Student("Child", 12)
# Class constructor and function call
print(obj2.name)
print(obj2.age)
obj2.adult(obj2.name, obj2.age)

Code explanation

  • Lines 2–13: It creates a class, Person, which is the parent class here.

  • Line 15: It creates a class, Student, which is derived from the Person class.

  • Line 29: It creates an object for the Student class.

  • Lines 31–33: It calls constructors and functions of the parent class, Person, because obj2 is an object of the Student class, which inherits the Person class.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved