Skip to the solution
MediumDSA11 min read

What is composition versus inheritance?

1.0k views

The problem

Question presented to candidate: "People say 'favour composition over inheritance'. What is the difference between the two, can you show it in Python, and when is inheritance still the right choice?"

What a strong answer should cover:

  • Inheritance is an is-a relationship: the subclass gets every attribute and method of the base and can be used wherever the base is expected (substitutability)
  • Composition is a has-a relationship: the object holds other objects as attributes and calls them, exposing only its own interface
  • Why composition is often preferred: looser coupling, no fragile base class, parts can be swapped at runtime and replaced by fakes in tests, no subclass explosion when features combine
  • A concrete Python trap: subclassing dict and overriding __setitem__ is bypassed by dict.__init__ and update(); collections.UserDict (which wraps a dict) fixes it
  • When inheritance fits: a real is-a relationship, framework base classes and ABCs, small mixins; delegation with __getattr__ as a middle ground

Clarifying questions expected:

  • Is the new type genuinely a kind of the old one, usable everywhere the old one is?
  • Will behaviours need to be combined or swapped (formats, storage, transports)?

Code / implementation expected: Optional β€” the same feature built both ways, for example a Stack that inherits from list versus one that holds a list.

  • oop
  • composition

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonIs-a versus has-a: a list-based Stack and the dict subclass trap
PythonComposing behaviour from parts, swapping them at runtime, and delegation

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 51 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How do you run external commands with subprocess safely?

Continue