Inheritance is a fundamental concept in object-oriented programming (OOP) where a new class (subclass or derived class) is created by inheriting attributes and methods from an existing class (superclass or base class).
In Python, inheritance allows a class to reuse code and extend the functionality of another class.
Single Inheritance: A subclass inherits from only one superclass.
Multiple Inheritance: A subclass inherits from multiple superclasses.
Multilevel Inheritance: A subclass inherits from a superclass, and another subclass inherits from it, forming a chain of inheritance.
Hierarchical Inheritance: Multiple subclasses inherit from the same superclass.
Hybrid (or Cyclic) Inheritance: A combination of multiple and multilevel inheritance, leading to complex inheritance structures.
class BaseClass: # Base class attributes and methods class DerivedClass(BaseClass): # Derived class attributes and methods
In the inheritance technique, the sub/child class acquires the properties and can access all the data (attributes) and functions(methods) defined in the parent/base class. A child/sub class can also provide its specific implementation to the functions of the base/parent class.
# Create a custom class name Animal class Animal: # Initialize Constructor def __init__(self, name): self.name = name # Create speak in parent class named "speak" def speak(self): raise NotImplementedError("Subclass must implement abstract method") # Create a custom class name Dog class Dog(Animal): # Create speak in sub/child class named "speak" def speak(self): return f"{self.name} says Woof!" # Create a custom class name Cat class Cat(Animal): # Create speak in sub/child class named "speak" def speak(self): return f"{self.name} says Meow!" # Creating instances of derived classes dog = Dog("Buddy") cat = Cat("Whiskers") # Calling methods print(dog.speak()) # Output: Buddy says Woof! print(cat.speak()) # Output: Whiskers says Meow!
Animal is the base class with an abstract method speak().
Dog and Cat are derived classes that are inherited from the "Animal" class.
Both Dog and Cat classes override the speak() method with their own implementations.
Instances of Dog and Cat classes can call the speak() method, and each class provides its specific behaviour.