Dav*_*vy8 42 python introspection python-2.7
我已经看到了以下问题,但它并没有让我想到我想要的地方:如何在Python中获取当前模块中所有类的列表?
特别是,我不想要导入的类,例如,如果我有以下模块:
from my.namespace import MyBaseClass
from somewhere.else import SomeOtherClass
class NewClass(MyBaseClass):
pass
class AnotherClass(MyBaseClass):
pass
class YetAnotherClass(MyBaseClass):
pass
Run Code Online (Sandbox Code Playgroud)
如果我使用clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)
链接问题中的接受答案建议,它将返回MyBaseClass
并且SomeOtherClass
除了本模块中定义的3之外.
我怎么才能得到NewClass
,AnotherClass
而且YetAnotherClass
?
Ign*_*ams 25
检查__module__
类的属性以找出它所定义的模块.
piR*_*red 12
我为回答这么老的问题而道歉,但我觉得使用检查模块来解决这个问题并不舒服.我读过在生产中使用不安全的地方.
我得到了测试一个对象是如何检查一个变量是否为类的类的答案 ?
所以这是我的免检查解决方案
def classesinmodule(module):
md = module.__dict__
return [
md[c] for c in md if (
isinstance(md[c], type) and md[c].__module__ == module.__name__
)
]
classesinmodule(modulename)
Run Code Online (Sandbox Code Playgroud)
您可能还需要考虑使用标准库中的"Python类浏览器"模块:http: //docs.python.org/library/pyclbr.html
因为它实际上没有执行有问题的模块(它确实进行了简单的源检查),所以有一些特定的技术它不能正确理解,但是对于所有"普通"类定义,它将准确地描述它们.
小智 7
我使用了以下内容:
# Predicate to make sure the classes only come from the module in question
def pred(c):
return inspect.isclass(c) and c.__module__ == pred.__module__
# fetch all members of module __name__ matching 'pred'
classes = inspect.getmembers(sys.modules[__name__], pred)
Run Code Online (Sandbox Code Playgroud)
我不想输入当前的模块名称