根据字符串导入模块, 利用反射找到模块下的类,实例化。执行
# settings.py
NOTIFY_LIST = [
'notify.email.Email',
'notify.msg.Msg',
'notify.wechat.Wechat',
]
-----------------------------
# app.py
from notify import send_xxx
def run():
send_xxx("报警")
if __name__ == "__main__":
run()
----------------------------
# notify/__init__.py
# 根据字符串 导入模块
import settings
import importlib
def send_xxx(content):
for path in settings.NOTIFY_LIST:
# 'notify.email.Email',
# 'notify.msg.Msg',
# 'notify.wechat.Wechat',
module_path,class_name = path.rsplit('.',maxsplit=1)
# 根据字符串导入模块
module = importlib.import_module(module_path)
# 根据类名称去模块中获取类
cls = getattr(module,class_name)
# 根据类实例化
obj = cls()
obj.send(content)
-----------------------------
# notify/email.py
class Email(object):
def __init__(self):
pass
def send(self,content):
print("email send..")
# notify/msg.py
class Msg(object):
def __init__(self):
pass
def send(self,content):
print("msg send..")
# notify/wechat.py
class Wechat(object):
def __init__(self):
pass
def send(self,content):
print("wechat send..")