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 person s - 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] .
Some other articles
Y116 - Applying OO design techniques and best practise Defining an object that is a modified standard type in Python How to avoid too many recalculations within an object We not only teach PHP and Python - we teach good PHP and Python Practice! Really Simple Class and Inheritance example in Python This article Tips for writing a test program (Ruby / Python / Java) Plan your application before you start How do I set up a constant in Python? Testing code in Python - doctest, unittest and others Alpaca Case or Camel Case Good Programming practise - where to initialise variables Code quality counts Build on what you already have with OO Python - block insets help with documentation Think about your design even if you don't use full UML Code and code maintainance efficiency Y112 - Objects - Intermediate Nesting decorators Defining an object that is a modified standard type in Python with in Python - examples of use, and of defining your own context Object and Static methods - what is the difference; example in Python 3 Setting up and tearing down with the Python with keyword Deciding whether to use parameters, conditional statements or subclasses Spike solution, refactoring into encapsulated object methods - good design practise A good example of recursion - a real use in Python Changing what operators do on objects - a comparison across different programming languages Object factories in C++, Python, PHP and Perl Python base and inherited classes, test harness and unit testing - new examples Python Properties - how and why Really Simple Class and Inheritance example in Python This article Backquote, backtic, str and repr in Python - conversion object to string Metaclasses (Python) and Metatables (Lua) Static variables in functions - and better ways using objects A demonstration of how many Python facilities work together A list of special method and attribute names in Python Python - some common questions answered in code examples Defining static methods in Python Should Python classes each be in their own file? The Light bulb moment when people see how Object Orientation works in real use Python decorators - your own, staticmethod and classmethod Mixins example in Python Multiple inheritance in Python - complete working example The Multiple Inheritance Conundrum, interfaces and mixins Methods that run on classes (static methods) in Python How do I set up a constant in Python? TypeError: super() argument 1 must be type, not classobj (Python) Python - fresh examples of all the fundamentals Calling base class constructors Equality, sameness and identity - Python Using a utility method to construct objects of different types - Python Python - formatting objects What are factory and singleton classes? __new__ v __init__ - python constructor alternatives? Practical polymorphism in action Pieces of Python Comparison of Object Oriented Philosophy - Python, Java, C++, Perl Think about your design even if you don't use full UML Class, static and unbound variables Overloading of operators on standard objects in Python Using a Python dictionary as a holder of object attributes Q907 - Object Orientation: Design Techniques Associative objects - one object within another. Spike solution, refactoring into encapsulated object methods - good design practise The spirit of Java - delegating to classes Test driven development, and class design, from first principles (using C++) Using object orientation for non-physical objects Teaching OO - how to avoid lots of window switching early on Storing your intermediate data - what format should you you choose? This article From Structured to Object Oriented Programming. Rooms ready for guests - each time, every time, thanks to good system design When you should use Object Orientation even in a short program - Python example Spike solutions and refactoring - a Python example Why you should use objects even for short data manipulation programs in Ruby Designing your application - using UML techniques Your PHP website - how to factor and refactor to reduce growing pains Ruby - a training example that puts many language elements together to demonstrate the whole Object Oriented Programming for Structured Programmers - conversion training Comments in and on Perl - a case for extreme OO programming What is a factory method and why use one? - Example in Ruby Turning an exercise into the real thing with extreme programming Should Python classes each be in their own file? Program for reliability and efficiency - do not duplicate, but rather share and re-use Relationships between Java classes - inheritance, packaging and others The Light bulb moment when people see how Object Orientation works in real use Containment, Associative Objects, Inheritance, packages and modules What is a factory? The Multiple Inheritance Conundrum, interfaces and mixins Plan your application before you start Simples Object Oriented programming - a practical design example Planning! Designing a heirarcy of classes - getting inheritance right When should I use OO techniques? Teaching Object Oriented Java with Students and Ice Cream Object Oriented Tcl Object Oriented Programming in Perl - Course Object Relation Mapping (ORM) What are factory and singleton classes? Maintainable code - some positive advice Build on what you already have with OO Comparison of Object Oriented Philosophy - Python, Java, C++, Perl The Fag Packet Design Methodology Think about your design even if you don't use full UML Design - one name, one action Introduction to Object Oriented Programming Tapping in on resources OO - real benefits