94. Class Inheritance
Here are 10 Python snippets demonstrating class inheritance, where derived classes inherit functionality from base classes:
1. Simple Inheritance
class Animal:
def speak(self):
return "I make a sound"
class Dog(Animal):
pass
dog = Dog()
print(dog.speak()) # Output: I make a sound2. Overriding Methods
class Animal:
def speak(self):
return "I make a sound"
class Cat(Animal):
def speak(self):
return "Meow"
cat = Cat()
print(cat.speak()) # Output: Meow3. Calling Parent Class Methods
4. Adding New Attributes in Derived Class
5. Multiple Inheritance
6. Checking Inheritance with issubclass
7. Polymorphism with Inherited Classes
8. Abstract Base Classes
9. Method Resolution Order (MRO) in Multiple Inheritance
10. Private Attributes and Inheritance
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.
These snippets demonstrate the power and flexibility of class inheritance in Python!
Last updated