Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, what's the correct way to instantiate a class from a variable?

Suppose that I have class C.

I can write o = C() to create an instance of C and assign it to o.

However, what if I want to assign the class itself into a variable and then instantiate it?

For example, suppose that I have two classes, such as C1 and C2, and I want to do something like:

if (something):
   classToUse = C1
else:
   classToUse = C2

o = classToUse.instantiate()

What's the syntax for the actual instantiate()? Is a call to __new__() enough?

like image 1000
Uri Avatar asked Jul 27 '09 17:07

Uri


3 Answers

o = C2()

This will accomplish what you want. Or, in case you meant to use classToUse, simply use:

o = classToUse()

Hope this helps.

like image 176
André Eriksson Avatar answered Oct 07 '22 22:10

André Eriksson


You're almost there. Instead of calling an instantiate() method, just call the variable directly. It's assigned to the class, and classes are callable:

if (something):
    classToUse = C1
else:
    classToUse = C2

o = classToUse()
like image 24
Jeff Avatar answered Oct 07 '22 20:10

Jeff


It's simple, Python don't recognize where a varible is a class or function. It's just call that value.

class A:
   pass
B=A
b=B()
like image 38
Arpegius Avatar answered Oct 07 '22 20:10

Arpegius