Inheritance is a fundamental concept in object-oriented programming (OOP) that allows classes to inherit attributes and methods from other classes. It promotes code reuse and establishes a hierarchical relationship between classes.
In Python, inheritance is implemented using the following syntax:
class ChildClass(ParentClass):
# Child class definition
The child class inherits all attributes and methods from the parent class, also known as the base class or superclass.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
dog = Dog("Buddy")
print(dog.speak()) # Output: Buddy says Woof!
In this example, the Dog
class inherits from the Animal
class and overrides the speak
method.
super()
FunctionThe super()
function allows you to call methods from the parent class. It's particularly useful when you want to extend the functionality of a parent class method:
class Bird(Animal):
def __init__(self, name, wingspan):
super().__init__(name)
self.wingspan = wingspan
def speak(self):
return f"{self.name} chirps!"
parrot = Bird("Polly", 20)
print(parrot.speak()) # Output: Polly chirps!
In cases of multiple inheritance, Python uses the C3 linearization algorithm to determine the method resolution order. You can view the MRO using the __mro__
attribute or the mro()
method:
print(Bird.__mro__)
# Output: (<class '__main__.Bird'>, <class '__main__.Animal'>, <class 'object'>)
To fully understand inheritance in Python, it's helpful to explore these related topics:
By mastering inheritance, you'll be able to create more efficient, organized, and reusable code in your Python projects.