Inheritance
Inheritance allows a class to inherit attributes and methods from another class. The class that inherits is called the child class (or subclass); the class being inherited from is the parent class (or superclass). This promotes code reuse and hierarchical relationships.
Basic Inheritance
Place the parent class in parentheses after the child class name.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some sound"
class Dog(Animal):
def speak(self):
return f"{self.name} says woof!"
Calling Parent Methods with `super()`
Use `super()` to call the parent class's methods, especially useful to avoid redundancy in `__init__`.
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name) # call parent constructor
self.color = color
def speak(self):
return f"{self.name} says meow!"
Multiple Inheritance
Python supports multiple inheritance (a class can inherit from multiple parent classes). This can be powerful but should be used carefully to avoid complexity.
Two Minute Drill
- Inheritance lets a child class reuse and extend a parent class.
- Use `super()` to call parent methods (especially `__init__`).
- Method overriding allows child to provide its own implementation.
- Python supports multiple inheritance.
Need more clarification?
Drop us an email at career@quipoinfotech.com
