initialising a class by name

Krishnakant krmane at gmail.com
Wed Jan 14 00:46:58 EST 2009


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.
Is this possible in python and how?
To make things clear, let me give the real example.
there is an inventory management system and products belong to different
categories.
There are predefined categories in the database and for each category
there is a module which contains a class made out of pygtk.
This means what class gets instantiated and displayed in the gui depends
on the choice a user makes in the dropdown.
Now, I could have created a list of if conditions for all the categories
as in 
if categorySelection == "books":
	Books = BookForm()

However this is a problem because when there will be more than 100
categories there will be that many if conditions and this will make the
code uggly.
so my idea is to name the class exactly after the name of the category
so that when the user selects a category that name is used to initialise
the instance of that class.
So is it possible to initialise an instance of a class given its name
from a variable?
thanks and 
Happy hacking.
Krishnakant. 




More information about the Python-list mailing list