J
John O'Hagan
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
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