Hierarchical Inheritance in Python
- Get link
- X
- Other Apps
Hierarchical Inheritance in Python
Inheritance is a key concept in object-oriented programming (OOP) that allows us to create new classes based on existing classes. Hierarchical inheritance is a type of inheritance in which a class has multiple subclasses that inherit from it. This means that the subclasses inherit all the attributes and methods of the parent class, and can also add new attributes and methods of their own.
Here's an example of hierarchical inheritance in Python:
class Animal: def __init__(self, name): self.name = name def speak(self): print(f"{self.name} says something.") class Dog(Animal): def speak(self): print(f"{self.name} barks.") class Cat(Animal): def speak(self): print(f"{self.name} meows.") dog = Dog("Buddy") cat = Cat("Fluffy") dog.speak() # output: Buddy barks. cat.speak() # output: Fluffy meows.
In this example, we have a Animal
class that has an __init__()
method that initializes an instance variable name
. It also has a speak()
method that prints out something.
We then create two subclasses Dog
and Cat
that inherit from the Animal
class. Both subclasses have their own speak()
method that overrides the speak()
method of the parent class.
We then create instances of the Dog
and Cat
classes called dog
and cat
, respectively, and call their speak()
methods. The output shows that each subclass was able to use its own speak()
method to print out a different sound.
Hierarchical inheritance is useful when you have multiple subclasses that share common attributes and methods, but also have their own unique attributes and methods. It allows you to organize and structure your code in a way that promotes code reusability and modularity.
In conclusion, hierarchical inheritance is a powerful feature of object-oriented programming in Python that allows you to create new classes based on existing classes. It is a building block of OOP that promotes code reusability and modularity, and can be used to create multiple subclasses that share common attributes and methods, but also have their own unique attributes and methods.
Happy Learning!! Happy Coding!!
- Get link
- X
- Other Apps
Comments