Search⌘ K
AI Features

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.

Python
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def start_engine(self):
return f"The {self.make} {self.model} engine is running."
# Sedan inherits from Vehicle
class Sedan(Vehicle):
pass
# We can instantiate Sedan exactly like a Vehicle
my_car = Sedan("Toyota", "Camry")
print(my_car.start_engine())
  • Lines 1–7: We define a standard Vehicle class. 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):. ...