Confused about class relationships
Tim Roberts
timr at probo.com
Fri Nov 28 15:38:24 EST 2008
John O'Hagan <research at johnohagan.com> wrote:
>
>Apologies if this is a D.Q., I'm still learning to use classes, and this
>little problem has proved too specific to find in the tutorials.
>
>I have two classes with a relationship that I find confusing.
>
>One is called Engine, and it has a method (bar_builder) which generates
>instances of the other class, called Bar (not as in Foo but as in bar of
>music; inherits from list).
>
>Also, Bar takes the generating instance of Engine as an argument to its
>__init__ method:
>
>class Bar(list):
>
> def __init__(self, a_bar, args, engine):
> list.__init__ (self, a_bar)
> self[:] = a_bar
> self.args = args
> self.engine = engine
> #more instance attributes...
>
> #methods...
>
>class Engine:
>
> def __init__(self, args):
> self.args = args
> #more instance attributes...
>
> def bar_builder(self):
> #body of method generates lists...
> yield Bar([generated_list], args, self)
>
> #more methods...
>
>#(other stuff...)
>
>def main(args):
>
> engine = Engine(args)
> bars = engine.bar_builder()
> for a_bar in bars:
> #play the music!...
>
>While this works (to my surprise!) and solves the problem which motivated it
>(i.e. Engine instances need to pass some attributes to Bar instances ), it
>seems too convoluted. Should one class inherit the other? If so, which way
>around? Or is it fine as is?
You need to put on a philosophical hat for this. Inheritance is used for
an "is-a" relationship, where one thing "is-a" special type of another
thing. Is "Engine" a special type of "Bar"? Is "Bar" a generic type of
"Engine"? I think the answer is no, and because of that inheritance is not
the right answer.
>I'm hoping this is a common trap I've fallen into; I just haven't been able to
>get my head around it. (I'm a musician...)
Why do you think this is a trap? Engine creates Bars. Bars need to know
about the Engine. I think you have expressed that relationship properly.
When I have these kinds of philosophical debates over my own code, I always
try to summarize them in the comments inside the module, just so others can
get "inside my head" to understand the thinking that led to my design.
--
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.
More information about the Python-list
mailing list