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()?
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>
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With