When is a subclass not right?

Carl Banks pavlovevidence at gmail.com
Fri Aug 25 18:51:25 EDT 2006


David Ells wrote:
> Carl Banks wrote:

> > The classical advice in choosing whether to subclass or or use
> > attribute is whether its more an an "is a" or "has a" relationship.  If
> > it's more natural to say B is an A, then subclass.  If it's more
> > natural to say B has an A, then use an attribute.  But that's only a
> > rule of thumb.
> >
> > I personally find another question helpful.  If it's reasonable that B
> > could have more than one of A, regardless if it actually does, use an
> > attribute.  If it's unreasonable, subclass.  Again, rule of thumb.
>
> This is not always the defining line between when to use inheritance
> vs. when to use composition.

I really don't think a defining line exists.  Some situatations exist
where either will do, and as I've said I've often switched between them
as my code develops.  Sometimes the best choice is due to some
technicality.

"is a" vs "has a" is only a guideline, in situations where it isn't
obvious, to hopefully but not certainly avoid a future switch.  Same
thing for other guideline I posted.  If the guideline turns out to pick
the wrong way, big deal, you fix it when refactoring.

You're not afraid of refactoring, are you? :)


Carl Banks




More information about the Python-list mailing list