initialising a class by name

Nick Craig-Wood nick at craig-wood.com
Wed Jan 14 10:32:07 EST 2009


Krishnakant <hackingkk at gmail.com> wrote:
>  I liked this idea of dispatchTable.
>  is it possible to say some thing like 
>  inst = dispatchTable{"ham"}
>  according to me, inst will become the instance of class ham.
>  Another thing to note is that all the classes are in different modules.
>  So where do I create the dict of classes mapped with the name?

You could use a metaclass which will get round the problem, provided
all the classes have a common baseclass, eg

class BaseThing(object):
    registry = {}
    class __metaclass__(type):
        def __init__(cls, name, bases, dict):
            cls.registry[cls.__name__] = cls

class ThingOne(BaseThing):
    pass

class ThingTwo(BaseThing):
    pass

class ThingThree(BaseThing):
    pass

print BaseThing.registry["ThingOne"]
print BaseThing.registry["ThingTwo"]
print BaseThing.registry["ThingThree"]

Which prints

<class '__main__.ThingOne'>
<class '__main__.ThingTwo'>
<class '__main__.ThingThree'>

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list