[ACCEPTED]-In Python, what's the correct way to instantiate a class from a variable?-instantiation
o = C2()
This will accomplish what you want. Or, in 2 case you meant to use classToUse, simply 1 use:
o = classToUse()
Hope this helps.
You're almost there. Instead of calling 3 an instantiate() method, just call the variable 2 directly. It's assigned to the class, and 1 classes are callable:
if (something): classToUse = C1 else: classToUse = C2 o = classToUse()
It's simple, Python don't recognize where 2 a varible is a class or function. It's just 1 call that value.
class A: pass B=A b=B()
A class is an object just like anything 5 else, like an instance, a function, a string... a 4 class is an instance too. So you can store 3 it in a variable (or anywhere else that 2 you can store stuff), and call it with () no 1 matter where it comes from.
def f(): print "foo" class C: pass x = f x() # prints foo x = C instance = x() # instanciates C
More Related questions