gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:33:54 25 4
gpt4 key购买 nike

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

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

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

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

谁能解释这是为什么?

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

最佳答案

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

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

其中mod是加载的模块

关于python - 迭代动态导入的模块中定义的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7584418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com