initialising a class by name

Chris Rebert clp2 at rebertia.com
Wed Jan 14 03:20:21 EST 2009


On Wed, Jan 14, 2009 at 12:15 AM, Krishnakant <krmane at gmail.com> wrote:
> 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.

Aside from Steven's excellent idea, to use the getattr() technique
with your module scheme you'd probably also need to use __import__()
to dynamically import the right module.

Also, don't top-post. It makes following the conversation harder for readers.

Cheers,
Chris

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

> 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