By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,941 Members | 1,766 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,941 IT Pros & Developers. It's quick & easy.

Calling constructor of unknown classes

P: n/a
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
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a

"Lars Heuer" <py****@quixs.com> wrote in message
news:ma**************************************@pyth on.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

Jul 18 '05 #2

P: n/a
Hi John,
Since you know the module (you just imported it), do something
like this: klas = getattr(mod, "className") instance = klas()


Thanks. I tried something similar, but instead of my way, your way works. ;)

Best regards,
Lars
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.