sodcalculator

10 Tech How-To

Python Inheritance and Composition: A How-To Guide

Guide 10-60021 · Updated · Step by step

This guide shows you how to use inheritance and composition in Python to design flexible, reusable classes. You’ll learn when to use each approach, how to implement them, and common pitfalls to avoid. No prior knowledge beyond basic Python classes is required.

What You’ll Need

  • Python 3.6 or later installed on your system
  • A text editor or IDE (like VS Code, PyCharm, or IDLE)
  • Basic understanding of Python classes, methods, and attributes

Step-by-Step

  1. Understand the core concepts. Inheritance creates an “is-a” relationship: a subclass inherits attributes and methods from a parent class. Composition creates a “has-a” relationship: a class contains instances of other classes as attributes. For example, a Car is a Vehicle (inheritance), but a Car has an Engine (composition).
  2. Start with a simple inheritance example. Define a base class and a subclass that extends it. Use super().__init__() to initialize the parent’s attributes.
  3. Write the base class. Create a file, say animals.py, and define a class Animal with an __init__ method and a speak method.
  4. Create a subclass. Define Dog(Animal) and override the speak method. Call super().__init__(name) to set the name.
  5. Test the inheritance. Instantiate Dog and call its methods. Verify that it inherits the name attribute and overrides speak.
  6. Implement composition. Create a class Engine with its own attributes and methods. Then create a Car class that has an engine attribute, which is an instance of Engine.
  7. Use composition to delegate behavior. In Car, add a method start() that calls self.engine.start(). This shows how composition lets you reuse code without inheritance.
  8. Combine both patterns. For example, a ElectricCar could inherit from Car and use a Battery component. This demonstrates that they are not mutually exclusive.
  9. Use abstract base classes for shared interfaces. Import ABC and abstractmethod from abc to define methods that subclasses must implement. This is useful when you want to enforce a contract.
  10. Prefer composition over inheritance when possible. For code reuse, composition is often more flexible because it avoids deep inheritance hierarchies. Use inheritance only when there is a true “is-a” relationship and you want to reuse the parent’s implementation.

Common Mistakes

  • Forgetting to call super().__init__() in the subclass, leading to missing attributes.
  • Overusing inheritance for code reuse when composition would be simpler and more maintainable.
  • Creating deep inheritance chains (more than two or three levels) that become hard to understand and modify.
  • Using composition but not exposing the component’s methods, leading to verbose code that defeats the purpose.
  • Not using abstract base classes when you have a clear interface that multiple classes should follow.

Tips

  • Use isinstance() to check if an object is an instance of a class or its subclasses, but avoid overusing it; rely on duck typing when possible.
  • Keep your inheritance hierarchy shallow and focused. If you find yourself adding many optional features, composition is likely better.
  • In composition, expose the component’s methods through wrapper methods only if needed. Sometimes it’s fine to access the component directly (e.g., car.engine.start()).
  • Use @property to control access to attributes, especially in composed classes.
  • Document your design decisions: note why you chose inheritance or composition for a particular relationship.

Troubleshooting

  • Subclass doesn’t have parent’s attributes: Ensure you call super().__init__() in the subclass’s __init__. If the parent’s __init__ requires arguments, pass them.
  • AttributeError when using composition: Check that you actually created the component instance in the __init__ method. For example, self.engine = Engine().
  • Method overriding not working: Make sure the method name matches exactly, and that you’re not accidentally hiding it with a different name.
  • Multiple inheritance issues: If you use multiple inheritance, be aware of the MRO (method resolution order). Use super() consistently to avoid diamond problems.
  • Circular imports: If your composed classes are in separate modules, avoid importing each other at the top level. Use local imports inside methods or restructure your modules.

Frequently Asked Questions

What is the difference between inheritance and composition?

Inheritance is an “is-a” relationship: a subclass is a type of the parent. Composition is a “has-a” relationship: a class contains another class as a component. Inheritance gives you automatic access to parent methods, while composition gives you more flexibility and avoids tight coupling.

When should I use inheritance instead of composition?

Use inheritance when you have a clear hierarchical relationship and you want to reuse the parent’s implementation, especially when you need to override methods. Use composition when you want to combine independent behaviors or when the relationship is not strictly “is-a”.

Can I use both inheritance and composition together?

Yes, absolutely. For example, a ElectricCar can inherit from Car (inheritance) and also have a Battery component (composition). This is a common and powerful pattern.

What is an abstract base class and why use it?

An abstract base class (ABC) defines methods that subclasses must implement. It ensures a consistent interface. Use it when you have multiple classes that should share the same methods but implement them differently.

Does composition replace inheritance entirely?

No. Some problems are naturally hierarchical, like Dog is a Animal. Composition is often preferred for code reuse, but inheritance is still valuable for polymorphism and when you need to treat subclasses as their parent type.

How do I decide between inheritance and composition for my project?

Ask yourself: “Is this a true “is-a” relationship?” If yes, and you need to reuse the parent’s methods, use inheritance. Otherwise, use composition. Also, consider how likely the relationship is to change; composition is easier to refactor.

Related

General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.

More in this bed

The whole Tech How-To bed →