python 动态加载类和函数的方法

本文介绍如何使用Python动态加载类和函数。通过glob.glob()查找指定目录下的所有符合特定后缀的文件,并利用__import__()和getattr()实现模块及类的动态加载,最后实例化这些类并展示运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python 动态加载类和函数的方法

用到的python 函数

  1. glob.glob()glob:文件名模式匹配,可以用通配符来筛选文件名。
  2. __import__()函数用于动态加载模块 。如果一个模块经常变化就可以使用该方法来动态载入。
  3. getattr()函数用于动态加载类

代码如下:

已知文件的目录结构如下:

|—modelset

​ |—IdentityModel.py

​ |—IncomeConsumeModel.py

|—main.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()

IdentityModel.py

#coding:utf-8
import sys
class IdentityModel():
    def __init__(self):
        print "IdentityModel 。。。"

IncomeConsumeModel.py

#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’>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值