Identifying a class type - bad practice?

James Harris james.harris.1 at googlemail.com
Tue Aug 18 13:09:29 EDT 2009


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. Two options appear to be useful: __class__
and isinstance. I know the latter will match the instance against any
superclass and the former will match one class only.

My question is: is this the Pythonic way to deal with such a tree? Is
there a better way? In C I would use structs where one field was a tag
indicating the kind of struct.

James



More information about the Python-list mailing list