Explain Inheritance in Python with an example
Inheritance is an important concept in object-oriented programming that allows a class to inherit properties and methods from a parent class. It allows for code reuse and helps to reduce redundancy in the codebase.
Here is an example of inheritance in Python:
In this example, we have a base class Animal with a name and species attribute and a method make_sound(). We then have two subclasses, Cat and Dog, that inherit from the Animal class. The Cat class has an additional breed and toy attribute and a method play(), while the Dog class has an additional breed attribute and overrides the make_sound() method from the Animal class.
When we create an instance of the Cat class, it will have all the attributes and methods of the Animal class, as well as its own attributes and methods. The same is true for the Dog class.
In this way, inheritance allows us to create a class hierarchy where more specialized classes inherit properties and methods from more general classes. It is a useful way to organize code and promote code reuse in object-oriented programming.
Leave a Comment