Inheritance and Code Reuse
Explore inheritance and code reuse in Python's object-oriented programming. Understand how subclasses reuse and extend parent class attributes and methods, the method resolution order, and when to use inheritance versus composition for cleaner, maintainable code.
Object-oriented programming allows developers to create specialized versions of existing classes without rewriting shared logic. In composition, complex objects are built by combining smaller components. This pattern represents a “has-a” relationship. In other cases, objects represent specialized forms of a more general type. For example, a sedan is a vehicle, and a truck is also a vehicle. This “is-a” relationship is modeled using inheritance. Inheritance allows a base class to define shared logic that specialized classes reuse. This reduces duplication and supports the DRY (Don’t Repeat Yourself) principle.
The “is-a” relationship
Inheritance allows a new class, called the subclass or child class, to acquire the attributes and methods of an existing class, known as the superclass or parent class. This models an is-a relationship, where the child represents a more specialized form of the parent.
In Python, inheritance is declared by placing the parent class name in parentheses after the child class name. If the child class defines no additional attributes or methods (using pass), it behaves exactly like the parent class, inheriting all of its functionality unchanged.
Lines 1–7: We define a standard
Vehicleclass. This acts as our generic blueprint, defining attributes (make,model) and behaviors (start_engine) that all vehicles share.Line 10: We declare
class Sedan(Vehicle):. ...