Python equivalent for Ruby's ObjectSpace?
I've a name of a class stored in var, which I need to create an object from. However I do not know in which module it is defined (if I did, I would just call getattr(module,var), but I do know it's im开发者_运维知识库ported.
Should I go over every module and test if the class is defined there ? How do I do it in python ?
What if I have the module + class in the same var, how can I create an object from it ? (ie var = 'module.class') Cheers, Ze
globals()[classname]
should do it.
More code: http://code.activestate.com/recipes/285262/
Classes are not added to a global registry in Python by default. You'll need to iterate over all imported modules and look for it.
Rather than storing the classname as a string, why don't you store the class object in the var, so you can instantiate it directly.
>>> class A(object):
... def __init__(self):
... print 'A new object created'
...
>>> class_object = A
>>> object = class_object()
A new object created
>>>
精彩评论