Main Content

Inheritance, Composition and Associated objects - when to use which - Python example

Archive - Originally posted on "The Horse's Mouth" - 2012-10-10 08:44:03 - Graham Ellis

• Inheritance is where one object is based on another.

• Composition is where one object contains another.

Question: Which should I use?

Answer: Probably BOTH!

On yesterday's Python course, the question came up, and I wrote an illustrative answer - source code [here]. The scenario we took was a restaurant.

We have tables of various shapes - rectangular ones, square ones, and circular ones. They're all based on a base class called table as all tables, no matter what shape, have some properties in common. And then we inherit from that base class to give somewhat updated table subclasses for each shape adding in the extra logic to work out how many people can be seated without being on the corners.

We also have persons - staff and customers - which have some features in common (such as names) but some differences in their other properties. Again, that's a case of inheritance.

The next step is to say that we have a member of staff responsible for each table, and multiple customers (perhaps) seated at each table. And that's where our composite / associated objects come into play. We don't want to add all the attributes of a staff member to a table - we just want to have a contained or associated object of type staff in our object of type table, and a list of objects of type customer in our object of type table.

The diagram, drawn using "class" and "object" tables in a UML-like way, shows these various relationships.

Update ... the course carried on the following day, and I added various static methods including a factory, comparators, and overrode the print method for some objects. The final source code is [here].