更好的利用配置文件和importlib
需求:做不同的操作时只需修改配置文件即可完成
# message/email.py from .base import Base # 子类必须实现send方法,否则抛出异常 class Email(Base): """ 发送邮件提醒相关 """ def __init__(self): """ 邮箱相关数据初始化 """ self.username = 'zhou' self.pwd = '123' def send(self,msg): pass
#message/msg.py from .base import Base class Msg(Base): """ 发送短信提醒相关 """ def __init__(self): """ 短信相关数据初始化 """ self.username = 'asdf' self.pwd = 'asdf' def send(self, msg): pass
# settings.py MSG_LIST = [ "utils.message.email.Email", "utils.message.msg.Msg", "utils.message.wechat.WeChat", ]
# message/init.py import settings import importlib def send_msgs(msg): for path in settings.MSG_LIST: m,c = path.rsplit('.',maxsplit=1) md = importlib.import_module(m) #导入模块 obj = getattr(md,c)() # 利用反射找到方法 obj.send(msg) # 执行方法
#使用 from message import send_msgs send_msgs("xxxxx")
既然选择了远方,便是风雨兼程...