In this Python oops program, we will create a class with multilevel inheritance in Python. The program showcases inheritance hierarchy in Python. The ChildClass
inherits methods from both ParentClass
and GrandparentClass
, and an object created from the child class can access and invoke methods from all the ancestor classes as well as its own methods.
Create a class with multilevel inheritance
Steps to solve the program
- The GrandparentClass is a base class or parent class that defines a method called grandparent_method. This method prints “Grandparent method”.
- The ParentClass is a derived class or child class that inherits from GrandparentClass. It also defines its own method called parent_method, which prints “Parent method”.
- The ChildClass is another derived class or child class that inherits from ParentClass. It defines its own method called child_method, which prints “Child method”.
- An object obj is created using the ChildClass. Since ChildClass inherits from ParentClass, and ParentClass inherits from GrandparentClass, the object obj has access to the methods defined in all three classes.
- The obj.grandparent_method() call invokes the grandparent_method inherited from GrandparentClass, which prints “Grandparent method”.
- The obj.parent_method() call invokes the parent_method inherited from ParentClass, which prints “Parent method”.
- The obj.child_method() call invokes the child_method defined in the ChildClass, which prints “Child method”.
class GrandparentClass:
def grandparent_method(self):
print("Grandparent method")
class ParentClass(GrandparentClass):
def parent_method(self):
print("Parent method")
class ChildClass(ParentClass):
def child_method(self):
print("Child method")
# Create an object of the child class
obj = ChildClass()
obj.grandparent_method()
obj.parent_method()
obj.child_method()
Output:
Grandparent method
Parent method
Child method