[Tutor] subclassing across multiple modules
Brian van den Broek
bvande at po-box.mcgill.ca
Fri Mar 18 00:32:50 CET 2005
Hi all,
I'm uncertain of how to make use of OOP design across multiple
modules. (Actually, on reflection, I'm not certain the multiple
modules aspect is central.) I'm also uncertain of how to frame the
question well, so please bear with me :-)
A schematic of what I have (with fake names for ease of example) is a
base module Toolkit.py and I want to write a module Application.py
which specializes the behaviour of the Toolkit.py classes. (I'm using
old-style classes, but don't feel committed to that choice.)
Toolkit.py defines:
class Tree
class Node
class Node1(Node)
class Node2(Node)
(other Node subclasses, too, but I'm simplifying.)
The Tree class contains a parser method to parse a file. It reads the
file, breaking it into chunks, and for each chunk, does the following:
if some_condition_on_chunk_contents:
node = Node1(chunk_contents)
else:
node = Node2(chunk_contents)
self.nodes.append(node)
Application.py will define
class Tree(Toolkit.Tree)
class Node(Toolkit.Node)
class Node1(Node, Toolkit.Node1)
class Node2(Node, Toolkit.Node2)
In all cases, a few methods will be added. I had no plans to override
existing methods.
My problem is that I want Application.Tree.parser to create
Application.Node1 and Application.Node2 instances when parsing a file.
From testing around with simpler cases, it seems as though unless I
override Toolkit.Tree.parser in Application.Tree, the inherited
Tree.parser method will create Toolkit.Node1 and Node2 objects, which
isn't what I want.
Toolkit.Tree.parser is my longest Tree method, and I definitely think
it would be bad to just copy and paste the method def into
Application.Tree so make the node = Node1(), etc. lines create an
Application.Node1, etc. object.
The best I have come up with is to replace the Toolkit.Tree.parser
lines of the form:
node = Node1(chunk_contents)
with lines like
node = self.get_Node1(chunk_contents)
and then have *both* Toolkit.Tree and Application.Tree define methods:
def get_Node1(self, chunk_contents):
return Node1(chunk_contents)
(like lines and methods for Node2)
This works in my test case, but still involves Copy and Paste of the
identical methods get_Node1 (and get_Node2) in both modules. Smelly. :-P
So, how can I make the lines like
node = Node1(chunk_contents)
of the Toolkit.Tree.parser method say something that means "create a
Node1 instance where Node1 is as defined in the module that defines
the instantiated Tree class" so that an instance of Application.Tree
creates instances of Application.Node1? Is that doable? Or, is some
other design indicated?
Thanks for making it to the end of the question! :-)
Best to all,
Brian vdB
More information about the Tutor
mailing list