Calling constructor of unknown classes

John Roth newsgroups at jhrothjr.com
Sat May 8 09:22:34 EDT 2004


"Lars Heuer" <python at quixs.com> wrote in message
news:mailman.357.1084020587.25742.python-list at python.org...
> Hi all,
>
> I try to do the following:
>
>   map = {'some.thing':'ClassName'}
>
>   try:
>     mod = __import___(map.keys()[0], {}, {}, map.values()[0])
>
>     # Now I want to return an instance of the class in
>     # map.values()[0]
>
>     # I've to do something like "return mod.(map.values()[0])()"
>
>
> How to return the instance of the 'unknown' class? I've only the name
> as string. I tried eval, but I don't get it work.
>
> Thanks,
> Lars

Since you know the module (you just imported it), do something
like this:

klas = getattr(mod, "className")

instance = klas()

John Roth






More information about the Python-list mailing list