Creating instance

Lee Harr missive at frontiernet.net
Tue Apr 1 18:03:05 EST 2003


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')()





More information about the Python-list mailing list