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:

class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species
   
    def make_sound(self):
        print("Some generic animal sound")

class Cat(Animal):
    def __init__(self, name, breed, toy):
        super().__init__(name, species="Cat") # Call the superclass's constructor
        self.breed = breed
        self.toy = toy
   
    def play(self):
        print(f"{self.name} plays with {self.toy}")

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name, species="Dog") # Call the superclass's constructor
        self.breed = breed
   
    def make_sound(self):
        print("Bark")

cat1 = Cat("Kitty", "Siamese", "Ball")
cat1.play()
cat1.make_sound()

dog1 = Dog("Rover", "Labrador")
dog1.make_sound()


 

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.

No comments

Powered by Blogger.