[ACCEPTED]-In Python, what's the correct way to instantiate a class from a variable?-instantiation

Accepted answer
Score: 18
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.

Score: 12

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
    classToUse = C2

o = classToUse()
Score: 2

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:
Score: 0

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