2024-03-28 18:59:19 发布
网友
我使用这一行来获取脚本中使用的所有类:
clsmembers = inspect.getmembers(sys.modules[__name__], inspect.isclass)
有没有一种(通用的)方法可以过滤掉脚本中创建的类以外的所有类(我不需要导入的类的名称。)
简单地在所有元素上循环并检查__main__太难看了
__main__
检查这些类的__module__属性:
__module__
clsmembers = [c for c in inspect.getmembers(sys.modules[__name__], inspect.isclass) if c[1].__module__ == __name__]
演示:
>>> import inspect >>> import sys >>> class Foo(object): pass ... >>> from json import * >>> inspect.getmembers(sys.modules[__name__], inspect.isclass) [('Foo', <class '__main__.Foo'>), ('JSONDecoder', <class 'json.decoder.JSONDecoder'>), ('JSONEncoder', <class 'json.encoder.JSONEncoder'>)] >>> [c for c in inspect.getmembers(sys.modules[__name__], inspect.isclass) if c[1].__module__ == __name__] [('Foo', <class '__main__.Foo'>)]
检查这些类的
__module__
属性:演示:
相关问题 更多 >
编程相关推荐