Identifying a class type - bad practice?

André andre.roberge at gmail.com
Tue Aug 18 21:24:18 CEST 2009


On Aug 18, 2:09 pm, 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. 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

I would probably go with hasattr(instance, 'what_I_want')

André



More information about the Python-list mailing list