tags:

views:

65

answers:

3

Hello,
I have list of class names and want to create their instances dynamically. for example:

names=[
'foo.baa.a',
'foo.daa.c',
'foo.AA',
 ....
]

def save(cName, argument):
 aa = create_instance(cName) # how to do it?
 aa.save(argument)

save(random_from(names), arg)

How to dynamically create that instances in Python? thanks!

A: 

Hi there,

You can use the python builtin eval() statement to instantiate your classes. Like this:

aa = eval(cName)()
hb2pencil
+1  A: 

This is often referred to as reflection or sometimes introspection. Check out a similar questions that have an answer for what you are trying to do:

Does Python Have An Equivalent to Java Class forname

Can You Use a String to Instantiate a Class in Python

Scott Lance
Some of those examples use `__import__`, for newer code you can switch to `importlib` http://docs.python.org/dev/library/importlib.html . (py>=2.7 | >=3.1)
DiggyF
+1  A: 

You can often avoid the string processing part of this entirely.

import foo.baa 
import foo.AA
import foo

classes = [ foo.baa.a, foo.daa.c, foo.AA ]

def save(theClass, argument):
   aa = theClass()
   aa.save(argument)

save(random.choice(classes), arg)

Note that we don't use a string representation of the name of the class.

In Python, you can just use the class itself.

S.Lott