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 J开发者_如何学JAVAava 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>
>>>
精彩评论