Python Practice › OOP Programs › Program 12
Hierarchical inheritance
Write a Python program that demonstrates hierarchical inheritance.
Output
I am a Square I am a Circle
Approach
- Several children share one parent.
Solution
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.