initialising a class by name

Krishnakant hackingkk at gmail.com
Wed Jan 14 03:23:52 EST 2009


Hi steevan,
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?
happy hacking.
Krishnakant. 
On Wed, 2009-01-14 at 07:50 +0000, Steven D'Aprano wrote:
> On Wed, 14 Jan 2009 11:16:58 +0530, Krishnakant wrote:
> 
> > hello all,
> > I have a strange situation where I have to load initiate an instance of
> > a class at run-time with the name given by the user from a dropdown
> > list.
> 
> Not strange at all.
> 
> > Is this possible in python and how?
> 
> Of course. Just use a dispatch table. Use a dict to map user strings to 
> classes:
> 
> 
> >>> class Spam(object): pass
> ...
> >>> class Ham(object): pass
> ...
> >>> dispatch_table = {"Spam": Spam, "Ham": Ham}
> >>> dispatch_table["Ham"]()
> <__main__.Ham object at 0xb7ea2f8c>
> 
> 
> The keys don't even have to be the name of the class, they can be 
> whatever input your users can give:
> 
> >>> dispatch_table["Yummy meat-like product"] = Spam
> >>> dispatch_table["Yummy meat-like product"]()
> <__main__.Spam object at 0xb7ea2f6c>
> 
> 
> You can even automate it:
> 
> >>> dispatch_table = {}
> >>> for name in dir():
> ...     obj = globals()[name]
> ...     if type(obj) == type:
> ...         dispatch_table[name] = obj
> ...
> >>> dispatch_table
> {'Ham': <class '__main__.Ham'>, 'Spam': <class '__main__.Spam'>}
> 
> 
> 




More information about the Python-list mailing list