Identifying a class type - bad practice?

Chris Rebert clp2 at rebertia.com
Tue Aug 18 16:50:27 EDT 2009


On Tue, Aug 18, 2009 at 10:09 AM, James
Harris<james.harris.1 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

?

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list