initialising a class by name
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Wed Jan 14 02:50:47 EST 2009
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'>}
--
Steven
More information about the Python-list
mailing list