Variable class instantiation

Richard Thomas chardster at gmail.com
Fri Dec 11 05:06:35 EST 2009


On Dec 11, 9:26 am, Jan Mach <jan.m... at cesnet.cz> wrote:
> Hi everybody,
> I am currently solving the following problem and I am stuck. I am trying
> to create instance of the class of variable name. I know, that the
> following works:
>
> if (something):
>     classToUse = C1
> else:
>     classToUse = C2
>
> o = classToUse()
>
> ,but this is not what I want. I need to have the class name in the string and then
> instantiate it:
>
> (this does not work of course)
> classToUse = "C1"
> o = classToUse()
>
> It is because I don`t know at the moment what the name of the class will be, I will
> load it from the file or pass it as argument. Does anyone know what is the correct syntax
> to accomplish this?
>
> Thanks for your time in advance
>
> Jan Mach
>
>  smime.p7s
> 4KViewDownload

You can always do eval(my_string) to get the class object.

Better I think is to make an explicit dictionary of options (much
safer).

classes = dict((cls.__name__, cls) for cls in (C1, C2))
classes["C1"] # gives you C1
classes["C2"] # gives you C2

Richard.



More information about the Python-list mailing list