Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection in python

I'm trying to find some info on reflection in python. I found a wikipedia article which gave this as a code snippet:

# without reflection
Foo().hello()

# with reflection
getattr(globals()['Foo'](), 'hello')()

I wasn't able to get this to work. What I really need is a way to just instantiate the object. So if I have a string 'Foo' I want to be able to get an object of type Foo. Like in java I could say something like: Class.forName("Foo")

Just found this...wonder why I couldn't find this before: Does python have an equivalent to Java Class.forName()?

like image 926
JPC Avatar asked Sep 02 '26 07:09

JPC


1 Answers

What I really need is a way to just instantiate the object.

That's what the globals()['Foo']() part does.

And it works for me:

>>> class Foo:
...   def __init__(self): print "Created a Foo!"
...
>>> globals()['Foo']()
Created a Foo!
<__main__.Foo instance at 0x02A33350>
>>>
like image 140
Karl Knechtel Avatar answered Sep 03 '26 23:09

Karl Knechtel