Creating instance

Salvatore salvatore at wanadoo.fr
Thu Apr 3 19:15:17 CEST 2003


Lee Harr wrote:

> In article <b6d191$j7s$1 at news-reader12.wanadoo.fr>, Salvatore wrote:
> 
>>Hello,
>>
>>I would like to create an instance of class
>>from the string name of the class
>>
>>class Foo:
>>	pass
>>
>>classname = 'Foo'
>>instance = create_instance('Foo')
>>
>>
> 
> 
> 
> I think it depends on which namespace the class lives in,
> and where you want to get at it from.
> 
> In the interactive interpreter, you might do:
> 
> class Foo:
>     pass
> instance = locals()['Foo']()
> 
> 
> 
> If the class lived in a module, say FooMod.py you could do:
> 
> # FooMod.py
> import FooMod
> 
> class Foo:
>     pass
> instance = getattr(FooMod, 'Foo')()
> 
Great too ;-)





More information about the Python-list mailing list