94. Class Inheritance

Here are 10 Python snippets demonstrating class inheritance, where derived classes inherit functionality from base classes:


1. Simple Inheritance

Copy

class Animal:
    def speak(self):
        return "I make a sound"

class Dog(Animal):
    pass

dog = Dog()
print(dog.speak())  # Output: I make a sound

2. Overriding Methods

Copy

class Animal:
    def speak(self):
        return "I make a sound"

class Cat(Animal):
    def speak(self):
        return "Meow"

cat = Cat()
print(cat.speak())  # Output: Meow

3. Calling Parent Class Methods

Copy


4. Adding New Attributes in Derived Class

Copy


5. Multiple Inheritance

Copy


6. Checking Inheritance with issubclass

Copy


7. Polymorphism with Inherited Classes

Copy


8. Abstract Base Classes

Copy


9. Method Resolution Order (MRO) in Multiple Inheritance

Copy


10. Private Attributes and Inheritance

Copy


Key Points:

  • Inheritance enables code reuse.

  • Overriding methods allows for specialized behavior in derived classes.

  • Use super() to call parent class methods.

  • Python supports multiple inheritance, but it's essential to understand the method resolution order (MRO).

  • Use abstract base classes (ABC) to define interfaces.

Last updated