当前位置:   article > 正文

python中字符串导入模块 importlib介绍

import 根据字符串 导入

字符串导入模块importlib

  1. # 模块:importlib
  2. import importlib
  3. res = 'myfile.b'
  4. ret = importlib.import_module(res) # 相当于:from myfile import b
  5. # 该方法最小只能到py文件名
  6. print(ret)
  7. from myfile import b
  8. print(b)

importlib应用场景

# 需求:发送通知的功能,发微信、qq、邮箱,同时通过这三个功能给客户发消息,可以随时禁止某一个板块的通知(只给微信qq发送通知,不给邮箱发)'
运行

普通版本:

功能文件:notify.py

  1. # 简单模拟三个功能
  2. def wechat(content):
  3. print('微信通知:%s'%content)
  4. def qq(content):
  5. print('qq通知:%s'%content)
  6. def email(content):
  7. print('email通知:%s'%content)
'
运行

启动文件:start.py

  1. from notify import * # 导入所有的函数
  2. def send_all(content): # 定义一个函数执行所有的功能函数
  3. wechat(content)
  4. qq(content)
  5. email(content)
  6. if __name__ == '__main__':
  7. send_all('你的特别关心给你发消息了') # 执行执行函数触发所有的功能函数

高阶版本:

创建一个notify文件夹,下面存储的都是功能模块,那么这就相当于一个包,包就需要有一个__init__.py文件,如果想要找包下面的所有模块的话,就直接通过__init__.py文件即可。

settings.py

  1. NOTIFY_LIST = [
  2. 'notify.email.Email', # 存储各功能模块的路径
  3. 'notify.qq.QQ',
  4. 'notify.wechat.Wechat',
  5. ]
'
运行

notify文件夹下:wechat.py

  1. class Wechat(object):
  2. def __int__(self):
  3. pass # 发送微信需要做的前期准备
  4. def send(self,content):
  5. print('微信通知:%s'%content)
'
运行

notify文件夹下:qq.py

  1. class QQ(object):
  2. def __int__(self):
  3. pass # 发送qq需要做的前期准备
  4. def send(self, content):
  5. print('QQ通知:%s' % content)
'
运行

notify文件夹下:email.py

  1. class Email(object):
  2. def __int__(self):
  3. pass # 发送email需要做的前期准备
  4. def send(self, content):
  5. print('邮箱通知:%s' % content)
'
运行

notify文件夹下:_ init_.py

  1. import settings
  2. import importlib
  3. # 定义一个send_all方法
  4. def send_all(content):
  5. for path_str in settings.NOTIFY_LIST: # 这样就拿到的是settings下的列表:'notify.email.Email',
  6. module_path, class_name = path_str.rsplit('.',maxsplit=1) # 使用字符串右切割:以 . 来切割切一位
  7. # 这样解压复制:module_path = notify.email class_name=Email
  8. # 利用字符串的导入:notify.email
  9. module = importlib.import_module(module_path) # 返回的是一个对象
  10. # 这样就相当于:from notify import email
  11. # 运用反射:拿到module对象里的class_name(Email)类
  12. cls = getattr(module,class_name)
  13. # 生成类的对象
  14. obj = cls()
  15. # 利用鸭子类型直接调用send方法
  16. obj.send(content)

启动文件:start.py

  1. import notify
  2. notify.send_all('特别关心下线了')

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/985101
推荐阅读
相关标签
  

闽ICP备14008679号