Inheritance
Understand how to use inheritance in Python to create subclasses that inherit attributes and methods from parent classes.
Concept
A mechanism to create a new class (subclasses) that inherits attributes and methods from an existing class (parent classes). It allows for code reuse and establishes a relationship between classes.
Type of Inheritance | Description | Example |
---|---|---|
Single Inheritance | A subclass inherits from one parent class. | class Dog(Animal): pass |
Multiple Inheritance | A subclass inherits from multiple parent classes. | class FlyingDog(Dog, Bird): pass |
Multilevel Inheritance | A subclass inherits from a parent class, which in turn inherits from another parent class. | Animal -> Mammal -> Dog |
Hierarchical Inheritance | Multiple subclasses inherit from a single parent class. | Animal -> Dog, Cat, Bird |
Hybrid Inheritance | A combination of two or more types of inheritance. | class FlyingDog(Dog, Bird): pass where Dog and Bird are subclasses of Animal . |
Implementation
Single Inheritance
super().__init__(name, age)
is used to call the constructor of the parent class (Animal
) to initialize the inherited attributes.isinstance(dog, Animal)
checks ifdog
is an instance of theAnimal
class or its subclasses.
Multiple Inheritance
When a class inherits from multiple parent classes, the order is determined by the Method Resolution Order (MRO), which follows the C3 linearization algorithm. This ensures a consistent order of method resolution. The MRO can be checked using the __mro__
attribute or the mro()
method. The MRO is a depth-first, left-to-right traversal of the class hierarchy.
The MRO for this is FlyingDog -> Dog -> Bird
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Encapsulation
Understand how to use encapsulation in Python to bundle data and methods into a single unit (class) and restrict direct access to some of the object's components.
Polymorphism
Learn how to implement polymorphism in Python to use a single interface for different data types and allow methods to behave differently based on the object type.