initialising a class by name

Chris Rebert clp2 at rebertia.com
Wed Jan 14 08:55:21 CET 2009


On Tue, Jan 13, 2009 at 11:49 PM, Krishnakant <krmane at gmail.com> 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.
>> 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()?

getattr(x, 'y') <==> x.y

vars() gives a dict representing the current accessible variable
bindings (I should have instead recommended the related globals()
function)
globals() gives a dict representing the global variable bindings
For example:
#foo.py
class Foo(object):
    #code here

Foo()
#same as
globals()['Foo']()
#end of file

Cheers,
Chris

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



More information about the Python-list mailing list