initialising a class by name
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Wed Jan 14 03:23:07 EST 2009
On Wed, 14 Jan 2009 13:19:23 +0530, Krishnakant wrote:
> On Tue, 2009-01-13 at 21:51 -0800, Chris Rebert wrote:
>> Assuming all the classes are in the same module as the main program:
>>
>> instance = vars()[class_name](args, to, init)
>>
> The classes are not in the same module. Every glade window is coupled
> with one py file (module) containing one class that has the events for
> the glade file. Inshort, there is one class in one module and they are
> all seperate.
Just import the classes you need, and dispatch on them.
import spammodule, hammodule
dispatch_table = {
"Spam": spammodule.Spamclass, "Ham": hammodule.Hamclass}
# later
obj = dispatch_table[ user_input ]()
>> 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)
>>
> Can you explain the difference between getattr and var()?
They are completely different things. At an interactive prompt, type:
help(getattr)
help(var)
and read what they say.
--
Steven
More information about the Python-list
mailing list