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 attributesdef __init__(self, parameters):# Constructor methoddef methods(self, parameters):# Method definition# Inherits parentClassclass 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 attributesdef __init__(self, parameters):# Constructor methoddef parent_methods(self, parameters):# Method definition# Inherits parentClassclass childClass(parentClass):passobject_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.
The following is an executable example of a class inheritance method:
# Create a class "Person"class Person:# function to initialize the name and agedef __init__(self, name, age):self.name = nameself.age = age# class function to determine if a person is adult or notdef adult(self, name, age):if age>=18:print(name, "is an adult.")else:print(name, "is not an adult.")class Student(Person):passprint("Parent class object: ")# crearting a new object for Person classobj1 = Person("Parent", 22)# Class constructor and function callprint(obj1.name)print(obj1.age)obj1.adult(obj1.name, obj1.age)print("Child class object: ")# crearting a new object for Student classobj2 = Student("Child", 12)# Class constructor and function callprint(obj2.name)print(obj2.age)obj2.adult(obj2.name, obj2.age)
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