迭代动态导入的模块中定义的类

新手上路,请多包涵

我有一个来自动态导入的子包的模块;我如何遍历它包含的类?

我一直在导入模块并列出如下名称:

 package = current_module.__name__
package = package[:package.rindex(".")] # get the package
package = "%s.sub.%s"%(package,name) # make the name of the child
print "(loading package %s)"%package
module = __import__(package) # this succeeds
for name,obj in inspect.getmembers(module):
    print name,type(obj)

这只打印模块属性而不是模块定义的类类型:

 __builtins__ <type 'dict'>
__doc__ <type 'NoneType'>
__file__ <type 'str'>
__name__ <type 'str'>
__package__ <type 'NoneType'>
__path__ <type 'list'>
imported_package <type 'module'>

看来我的课程不在 __dict__ 除非 fromlist 是非空的!来自列表中的值似乎没有经过验证; [""] 似乎工作正常,突然出现了课程!

谁能解释这是为什么?

(标准 ubuntu python 2.7.1+ (r271:86832)

原文由 Will 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 604
2 个回答

示例:创建一个将名称映射到类的字典:

 dict([(name, cls) for name, cls in mod.__dict__.items() if isinstance(cls, type)])

其中 mod 是加载的模块

原文由 pvoosten 发布,翻译遵循 CC BY-SA 3.0 许可协议

方法一:

 import inspect
import mymodule

for name, obj in inspect.getmembers(mymodule):
    if inspect.isclass(obj):
        do stuff...

方法二:

 desired_classes = [obj for name, obj in somemodule.__dict__.items() if isinstance(obj, DesiredType)]

方法三:

在您要迭代的模块内部:

文件: mymodule.py

 class Dog:
    VOICE = 'haou'

class Cat:
    VOICE = 'meew'

class ImNotIncluded:
    VOICE = 'what a shame'

__all__ = ['Dog', 'Cat']
 >>> from mymodule import *
>>> Dog.VOICE
'haou'
>>> Cat.VOICE
'meew'
>>> ImNotIncluded.VOICE
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
NameError: name 'ImNotIncluded' is not defined

现在迭代你做:

 >>> for cls in map(mymodule.__dict__.get, mymodule.__all__): cls
...
<class 'mymodule.Dog'>
<class 'mymodule.Cat'>


原文由 ניר 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题