initialising a class by name

Chris Rebert clp2 at rebertia.com
Wed Jan 14 00:51:37 EST 2009


On Tue, Jan 13, 2009 at 9:46 PM, Krishnakant <krmane at gmail.com> 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.
> 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

Assuming all the classes are in the same module as the main program:

instance = vars()[class_name](args, to, init)

Assuming the classes are all in the same module "mod", which is
separate from the main program:

instance = getattr(mod, class_name)(args, to, init)

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list