In this Python oops program, we will create a class with hierarchical inheritance in Python. The program illustrates inheritance in Python with multiple child classes inheriting from a single-parent class.
Create a class with hierarchical inheritance
Steps to solve the program
- The ParentClass is a base class or parent class that defines a method called parent_method. This method prints “Parent method”.
- The ChildClass1 is a derived class or child class that inherits from ParentClass. It defines its own method called child_method1, which prints “Child 1 method”.
- The ChildClass2 is another derived class or child class that also inherits from ParentClass. It defines its own method called child_method2, which prints “Child 2 method”.
- Two objects, obj1 and obj2, are created using the ChildClass1 and ChildClass2, respectively.
- The obj1.parent_method() call invokes the parent_method inherited from ParentClass, which prints “Parent method”.
- The obj1.child_method1() call invokes the child_method1 defined in ChildClass1, which prints “Child 1 method”.
- Similarly, the obj2.parent_method() call invokes the parent_method inherited from ParentClass, which prints “Parent method”.
- The obj2.child_method2() call invokes the child_method2 defined in ChildClass2, which prints “Child 2 method”.
class ParentClass:
def parent_method(self):
print("Parent method")
class ChildClass1(ParentClass):
def child_method1(self):
print("Child 1 method")
class ChildClass2(ParentClass):
def child_method2(self):
print("Child 2 method")
# Create objects of the child classes
obj1 = ChildClass1()
obj2 = ChildClass2()
obj1.parent_method()
obj1.child_method1()
obj2.parent_method()
obj2.child_method2()
Output:
Parent method
Child 1 method
Parent method
Child 2 method
Related Articles
Python Class with Method Overloading.
Python Class with Method Overriding.
Write a Python Class Program with an Abstract method.
Write a Python Class program to create a class with data hiding.
Python Class Structure for School Management System.
Write a Python Class Structure for Employee Management Application.