15

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?

4 Answers 4

24
o = C2()

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

o = classToUse()

Hope this helps.

Sign up to request clarification or add additional context in comments.

5 Comments

So the semantics of adding () to a variable mean "treat as class and instantiate?"
() means "call this". Calling a class means instantiating it. Behind the scenes, calling something calls the call metamethod, which you may use to make for example class instances callable as well.
In the previous comment call should probably be __call__(). (I hope formatting works this time.)
Aye, I got bitten by formatting again. Properly stated: Behind the scenes, calling something calls the __call__() metamethod. Thanks, Bastien Léonard.
Also note that apply() had to be used for this purpose before 2.3.
14

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

Comments

2

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

Comments

0

A class is an object just like anything else, like an instance, a function, a string... a class is an instance too. So you can store it in a variable (or anywhere else that you can store stuff), and call it with () no matter where it comes from.

def f(): print "foo"

class C: pass

x = f
x() # prints foo

x = C
instance = x() # instanciates C

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.