Python Program to Show Inheritance
Intermediate · Classes and objects
Inheritance lets a new class, the child or subclass, reuse the attributes and methods of an existing class, the parent or base class, and add or change only what is different. This program has an Animal parent class and two child classes, Dog and Bird, that share its code but make their own sounds.
Program
Some animal has 4 legs Some animal makes a sound Bruno has 4 legs Bruno says Woof! Mithu has 2 legs Mithu says Tweet! Is Bruno an Animal? True Can Mithu fly? True
How it works
class Dog(Animal):makesDoga child ofAnimal, so a dog gets__init__,describe()andspeak()without writing them again.Dogdefines its ownspeak(), which replaces the parent's version for dogs only; this is called method overriding.Birdadds a new attribute, so its__init__first callssuper().__init__(name, 2)to letAnimalset the name and the two legs.- The loop calls the same two methods on every pet, and each object runs its own version, which is called polymorphism.
- One parent with several children, as here, is called hierarchical inheritance, and
isinstance()confirms that a dog is also an animal.
Other ways to write it
Multilevel inheritance
Hi, I am Ravi Hi, I am Meera from DPS Hi, I am Asha from KV Delhi, and I am a prefect
Each class builds on its parent's greet() by calling super().greet(), so a Prefect gets the text from all three levels. A chain like this is called multilevel inheritance.
Multiple inheritance
A duck can swim and can fly Parents of Duck: ['Swimmer', 'Flyer']
A class can inherit from more than one parent, and it gets the methods of all of them. pass means the class adds nothing of its own.
Try it yourself
Add a Cat class that inherits from Animal and says "Meow!", then add a cat to the pets list.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises