12. Problem to create a class with hierarchical inheritance in Python

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
  1. The ParentClass is a base class or parent class that defines a method called parent_method. This method prints “Parent method”.
  2. 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”.
  3. 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”.
  4. Two objects, obj1 and obj2, are created using the ChildClass1 and ChildClass2, respectively.
  5. The obj1.parent_method() call invokes the parent_method inherited from ParentClass, which prints “Parent method”.
  6. The obj1.child_method1() call invokes the child_method1 defined in ChildClass1, which prints “Child 1 method”.
  7. Similarly, the obj2.parent_method() call invokes the parent_method inherited from ParentClass, which prints “Parent method”.
  8. 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 Multilevel Inheritance.

Python Class with Method Overloading.

Leave a Comment