python: inheriting or composition

composition, dictionary, inheritance, python

Solution

Inheritance is very often abused. Unless your class is meant to be used as a generic dictionary with extra functionality, I would say composition is the way to go.

Saving forwarding calls is usually not a good enough reason for choosing inheritance.

From the Design Pattern book:

Favor object composition over class inheritance

Ideally you shouldn't have to create new components to achieve reuse. You should be able to get all the functionality you need by assembling existing components through object composition. But this is rarely the case, because the set of available components is never quite rich enough in practice. Reuse by inheritance makes it easier to make new components that can be composed with old ones. Inheritance and object composition thus work together.

Nevertheless, our experience is that designers overuse inheritance as a reuse technique and designs are often made more reusable (and simpler) by depending more on object composition."

The entire text is here: http://blog.platinumsolutions.com/node/129

Problem

Let's say that I have `class`, that uses some functionality of `dict`. I used to composite a `dict` object inside and provide some access from the outside, but recently thought about simply inheriting `dict` and adding some attributes and methods that I might require. Is it a good way to go, or should I stick to composition?

Original source