initialising a class by name

Krishnakant krmane at gmail.com
Wed Jan 14 03:15:05 EST 2009


Hi, 
So should I not use getattr()?
If I have one class in one module, then should I use global?
I found getattr() very easy to use, my only dowbt is that if there is
going to be one class per module then will it be a good idea?
some thing like module, class_name 
happy hacking.
Krishnakantt.
On Tue, 2009-01-13 at 23:55 -0800, Chris Rebert wrote:

> 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
> 




More information about the Python-list mailing list