Python Practice › OOP Programs › Program 12

Hierarchical inheritance

EasyOOP Programs · 12 of 48

Write a Python program that demonstrates hierarchical inheritance.

Advertisement
Output
I am a Square
I am a Circle

Approach

  1. Several children share one parent.

Solution

Python
class Shape:    def describe(self):        return f"I am a {type(self).__name__}" class Square(Shape):    pass class Circle(Shape):    pass for s in [Square(), Circle()]:    print(s.describe())
Output
I am a Square
I am a Circle

Line by line

Line 3

type(self) is the actual child class, so the shared method gives a different answer for each.

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Leave a Comment