[Tutor] inheritance vs aggregation in Python

Sean 'Shaleh' Perry shalehperry@attbi.com
Tue, 27 Aug 2002 10:54:57 -0700


On Tuesday 27 August 2002 10:53, Erik Price wrote:
> My understanding of inheritance and aggregation are pretty limited.  I
> have a question about them (in Python).
>
>  From what I understand, the primary benefit of inheritance (over
> aggregation) is that the object is of the same type as the ancestor
> object it is inheriting from.  This is important in Java and presumably
> in other strongly typed languages.
>
> However, aggregation of objects seems (to me) to be more flexible than
> inheriting from objects, since you don't limit yourself to just that
> type.
>
> So, then, in Python, typing isn't strongly enforced -- so then what is
> the advantage of inheritance vs simply aggregating an object that you
> might need?  (Other than any performance-related reasons, I'm asking
> this question in a theoretical rather than practical sense.)
>

Part of programming is creating something from a specification.  Inherita=
nce=20
often makes for a more clear implementation and leads to "self documentin=
g"=20
code.

The proverbial example uses animals or geometry.

Animal -> Bird -> Raven

For a more real world situation consider a Factory which makes Widgets.

Widget ->
  WidgetTypeI
  WidgetTypeII

a Widget may define a part number and a factory number (where was it made=
).

You could then use aggregation to group several Widgets into a Car for=20
instance.

In the OO literature Inheritance is called "is-a" and aggregation is call=
ed=20
"has-a".  'A bird is a animal' or 'A WidgetTypeI is a Widget' or 'A Car h=
as a=20
Windshield'.