Calling constructor of unknown classes

L

Lars Heuer

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
 
J

John Roth

Lars Heuer said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,197
Messages
2,571,040
Members
47,634
Latest member
RonnyBoelk

Latest Threads

Top