Class hierarchy problem

Joe Junior joe.fbs.junior at gmail.com
Tue Aug 6 12:23:58 EDT 2013


On Tue, Aug 6, 2013 at 12:36 PM, BrJohan <brjohan at gmail.com> wrote:
> On 06/08/2013 16:02, Chris Angelico wrote:
>
>>> My classhierarchy is like a multilevel tree where each non-leaf node
>>> (class)
>>> is given knowledge about its nearest subclasses and their 'capacities'.
>>>
>>> So, my idea is to let the 'upper' class recursively choose which of its
>>> nearest subclasses is the 'correct' one, until approaching a 'leaf' class
>>> from which the instance should be created. And, given my knowledge that a
>>> solution along the lines of this idea has been designed and was working,
>>> I'm
>>> still hopeful ... (or I'll have to investigate all those old backup-DVDs)
>>
>>
>> [ responding on-list - I hope it was mere oversight that had this come
>> privately to me alone ]
>>
>> This is code smell; this recursive search for the "right" class seems
>> likely to be wrong. Can you have the classes perhaps register
>> themselves in some way? On what basis is a superclass to determine
>> that one of its subclasses should handle this request?
>>
>> ChrisA
>>
>
>
> Consider a botanical classification system (somewhat analogous to my
> 'problem' as it effectively is related to classification of entities):
>
> A Domain should know about its Kingdoms,
> a Kingdom should know about its Phylums,
> ...
> a Genus should know about its Species.
>
> Of course it is possible to implement such a decision tree as a 'factory'.
> However, I would rather prefer to encapsulate those decisions at the class
> level where they 'belong'.
>
> BrJohan
> --

I think it's a "has a" vs a "is a" problem. A Domain has a Kingdom, a Kingdom is
not a Domain, so it shouldn't actually inherit Domain. In this case
you should use
composition instead of inheritance.

When you say that a A Domain should know about it's Kingdons note that you're
talking about a specific Domain and it's specific Kingdons, which
means, a Domain
instance and various Kingdom instances.

JoeS



More information about the Python-list mailing list