Identifying a class type - bad practice?

James Harris james.harris.1 at googlemail.com
Wed Aug 19 04:52:22 EDT 2009


On 18 Aug, 21:50, Chris Rebert <c... at rebertia.com> wrote:
> On Tue, Aug 18, 2009 at 10:09 AM, James
>
> Harris<james.harri... at googlemail.com> wrote:
> > I am writing some code to form a tree of nodes of different types. The
> > idea is to define one class per node type such as
>
> > class node_type_1(node):
> >  <specific properties by name including other node types>
> > class node_type_2(node):
> >  <specific properties by name including other node types>
> > etc
>
> > (Class "node" would hold any common properties).
>
> > When walking the tree I need to know what type of node I'm dealing
> > with so polymorphism isn't generally useful. The action to be taken
> > depends on the node type.
>
> I'm sure it relates to the exact type of tree you're walking and the
> calculation you're doing on it, but what is the reason why your code,
> which in the abstract sounds like it will vaguely resemble this:
>
> def walk_tree(tree):
>     if isinstance(tree, node_type_1):
>         #code
>         walk_tree(subtree)
>     elif isinstance(tree, node_type_2):
>         #code
>         walk_tree(subtree)
>     #etc...
>
> can't be written instead as:
>
> class node_type_1:
>     def walk_tree(self):
>         #code
>         self.subtree.walk()
>
> class node_type_2:
>     def walk_tree(self):
>         #code
>         self.subtree.walk()
>
> #etc

Interesting idea. This may be a better and a more OO solution than
what I had in mind. I'm not sure if I can use this but I'll see how it
fits in as the work progresses.

The tree is for a compiler. Initially the tree is for parsing of
source code. Then it will need to be processed and changed as further
compiler phases are written. I don't know yet whether it will be
easier to modify the tree or to create a new one for each phase.

So I guess whether I use the idea depends on the commonality of
operations.

James



More information about the Python-list mailing list