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?
o = C2()
This will accomplish what you want. Or, in case you meant to use classToUse, simply use:
o = classToUse()
Hope this helps.
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()
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With