Confused about class relationships

bieffe62 at bieffe62 at
Thu Nov 27 14:32:47 CET 2008

On 27 Nov, 06:20, John O'Hagan <resea... at> 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?
> 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...)
> John O'Hagan

if you need the engine to generate a (potentially) infinite sequence
of bars, this approach seems the most linear
you could do ...
Inheritance is for classes which share attribute/methods, which is not
the case ...

then, there are always many way to to the same thing, and sometime
they are equivalent but for the
programmer taste ...


More information about the Python-list mailing list