python 动态加载类和函数的方法
用到的python 函数
glob.glob()
glob:文件名模式匹配,可以用通配符来筛选文件名。__import__()
函数用于动态加载模块 。如果一个模块经常变化就可以使用该方法来动态载入。getattr()
函数用于动态加载类
代码如下:
已知文件的目录结构如下:
|—modelset
|—IdentityModel.py
|—IncomeConsumeModel.py
|—main.py
#coding:utf-8
import glob
import sys
import os
module_dir = "modelset"
module_suffix_extension = "Model.py"
def main():
current_dir = os.path.abspath(os.path.dirname(__file__))
for pkg in glob.glob('%s/%s/*%s' % (current_dir,module_dir,module_suffix_extension)) :
base_name = os.path.basename(pkg).split('.')[0] # 模块名
pkg_name = module_dir+'.'+base_name # 模块的路径
module = __import__(pkg_name,fromlist=[base_name]) # 导入模块,fromlist只会导入list目录
print "module type:", type(module)
model_class = getattr(module, base_name)#获取的是个类
print "model_class type:", type(model_class)
instance = model_class() #获取实例对象
print "instance type:", type(instance)
print "-"*30
if __name__ == "__main__":
main()
#coding:utf-8
import sys
class IdentityModel():
def __init__(self):
print "IdentityModel 。。。"
#coding:utf-8
import sys
class IncomeConsumeModel():
def __init__(self):
print "IncomeConsumeModel 。。。"
运行结果
module type: <type ‘module’>
model_class type: <type ‘classobj’>
IdentityModel 。。。
instance type: <type ‘instance’>
module type: <type ‘module’>
model_class type: <type ‘classobj’>
IncomeConsumeModel 。。。
instance type: <type ‘instance’>