import importlib res = 'myfile.b' ret = importlib.import_module(res) # from myfile import b # 该方法最小只能到py文件名 print(ret)
def send_all(content): for path_str in settings.NOTIFY_LIST: #'notify.email.Email' module_path,class_name = path_str.rsplit('.',maxsplit=1) # module_path = 'notify.email' class_name = 'Email' # 1 利用字符串导入模块 module = importlib.import_module(module_path) # from notify import email # 2 利用反射获取类名 cls = getattr(module,class_name) # Email、QQ、Wechat # 3 生成类的对象 obj = cls() # 4 利用鸭子类型直接调用send方法 obj.send(content)
实现直接#注销即可停用此服务,
django.middleware.csrf.CsrfViewMiddleware 等同于 from django.middleware.csrf import CsrfViewMiddleware
start.py:
import notify notify.send_all('快发工资了')
email.py:
class Email(object): def __init__(self): pass #发送邮箱徐璈做的前期准备工作 def send(self,content): print('邮箱通知:%s'%content)
qq.py:
class QQ(object): def __init__(self): pass #发送QQ徐璈做的前期准备工作 def send(self,content): print('QQ通知:%s'%content)
wechat.py:
class Wechat(object): def __init__(self): pass #发送微信徐璈做的前期准备工作 def send(self,content): print('微信通知:%s'%content)
__init__.py:
import setting import importlib def send_all(content): for path_str in setting.NOTIFY_LIST: module_path,class_name=path_str.rsplit('.',maxsplit=1) #module_path='notify.email' class_name='Email' #1.利用字符串导入模块 module=importlib.import_module(module_path) #2.利用反射获取类名 cls=getattr(module,class_name) #3.生成类的对象 obj=cls() #4.利用鸭子类型直接调用send方法 obj.send(content)
msg.py:
class Msg(object): def __init__(self): pass #发送短信徐璈做的前期准备工作 def send(self,content): print('短信通知:%s'%content)
setting.py:
NOTIFY_LIST=[ 'notify.email.Email', 'notify.qq.QQ', # 'notify.wechat.Wechat' 'notify.msg.Msg' ]
标签:importlib,module,content,send,模块,path,import,class From: https://www.cnblogs.com/97zs/p/18102198