开发者

Python equivalent for Ruby's ObjectSpace?

开发者 https://www.devze.com 2022-12-20 20:16 出处:网络
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

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
>>> 
0

精彩评论

暂无评论...
验证码 换一张
取 消