Basic Inheritance
Inheritance allows a class to inherit attributes and methods from another class. The class being inherited from is called the parent or base class, and the class that inherits is called the child or derived class.
# Parent class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
# Child class inheriting from Animal
class Dog(Animal):
def speak(self):
print(f"{self.name} barks")
# Using the classes
animal = Animal("Generic Animal")
dog = Dog("Rex")
animal.speak() # Output: Generic Animal makes a sound
dog.speak() # Output: Rex barks
The Dog class inherits all attributes and methods from Animal but can override them to provide specific implementations.
Multiple Inheritance
Python supports multiple inheritance, where a class can inherit from more than one parent class. This allows for combining features from multiple classes.
class Swimmer:
def swim(self):
print("Swimming!")
class Flyer:
def fly(self):
print("Flying!")
class Duck(Swimmer, Flyer):
pass
donald = Duck()
donald.swim() # Output: Swimming!
donald.fly() # Output: Flying!
Multiple inheritance can be powerful but should be used carefully to avoid complexity and the "diamond problem" where the same method is defined in multiple parent classes.
Method Resolution Order (MRO)
Python uses a specific order to search for methods in inheritance hierarchies. This is called the Method Resolution Order (MRO).
class A:
def process(self):
print("A processing")
class B(A):
def process(self):
print("B processing")
super().process()
class C(A):
def process(self):
print("C processing")
super().process()
class D(B, C):
def process(self):
print("D processing")
super().process()
d = D()
d.process()
# Output:
# D processing
# B processing
# C processing
# A processing
# View the MRO
print(D.__mro__)
# Output: (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
Python uses the C3 linearization algorithm to determine the MRO, which ensures a consistent and predictable order of method resolution.
Abstract Base Classes
Abstract Base Classes (ABCs) define a blueprint for other classes. They can't be instantiated themselves but can require that derived classes implement specific methods.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
# This will raise an error because Square doesn't implement perimeter()
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
rect = Rectangle(4, 5)
print(rect.area()) # Output: 20
print(rect.perimeter()) # Output: 18
# This will raise TypeError: Can't instantiate abstract class Square...
# square = Square(5)
Abstract Base Classes enforce a consistent interface across subclasses, making your code more maintainable and less prone to errors.
Python Inheritance Videos
Master Python inheritance with these handpicked YouTube tutorials:
Learn the fundamentals of inheritance:
Working with multiple parent classes:
Creating interfaces with ABCs:
Practical applications of inheritance: