Inheritance
Reuse code and build relationships between classes.
Inheritance is a mechanism where a new class (derived class or subclass) inherits attributes and methods from an existing class (base class or superclass). This allows you to create a hierarchy of classes that share common functionality while allowing specialization.
Understanding Inheritance
Section titled “Understanding Inheritance”Inheritance creates an “is-a” relationship. For example:
- A
Caris-aVehicle - A
Dogis-anAnimal - A
Manageris-anEmployee
Basic Inheritance
Section titled “Basic Inheritance”classDiagram
class Vehicle {
+brand: str
+model: str
+year: int
+start() str
+stop() str
+get_info() str
}
class Car {
+num_doors: int
+honk() str
}
class Motorcycle {
+bike_type: str
+wheelie() str
}
Vehicle <|-- Car
Vehicle <|-- Motorcycle
Method Overriding
Section titled “Method Overriding”Subclasses can override parent methods to provide specialized behavior:
Using super()
Section titled “Using super()”The super() function/keyword allows you to call methods from the parent class:
Real-World Example: E-commerce System
Section titled “Real-World Example: E-commerce System”Multiple Inheritance
Section titled “Multiple Inheritance”Method Resolution Order (MRO)
Section titled “Method Resolution Order (MRO)”Key Takeaways
Section titled “Key Takeaways”- Inheritance creates an “is-a” relationship between classes
- Subclasses inherit all attributes and methods from parent classes
- Method overriding allows subclasses to provide specialized behavior
super()is used to call parent class methods- Multiple inheritance allows a class to inherit from multiple parents
- MRO determines the order in which methods are resolved in multiple inheritance
- Use inheritance to reuse code and create specialized classes from general ones
Inheritance is powerful for creating class hierarchies where specialized classes extend and customize the behavior of more general classes.