python 鸭子类型
作者:互联网
django中有一个神奇的文件, 叫做 settings.py, 就是一些配置项, 比如类的配置项
通过字符串类加载类, 就需要类的路径
通过路径 + 类名, 生成类, 就需要 反射 中的 getattr
配置项的最终用法是, 通过配置, 不需要去改代码, 就能拓展或者关闭某些特定功能
1. 入口
import importlib from settings import SEND_MESSAGE_CONFIG def send_all(msg): for i in SEND_MESSAGE_CONFIG: package_path, class_name = i.rsplit('.', maxsplit=1) package = importlib.import_module(package_path) cls_name = getattr(package, class_name) cls = cls_name() cls.send(msg) if __name__ == '__main__': send_all("推送一条消息")
2. 配置项, 通过这一项决定推送哪些消息
# 推送消息配置 SEND_MESSAGE_CONFIG = [ 'send_message.wechat.WeChat', 'send_message.qq.QQ' ]
3. send_message 包下的两个文件
qq.py
wechat.py
class QQ(object): def send(self, msg): print('QQ消息: %s' % msg) class WeChat(object): def send(self, msg): print("微信消息: %s" % msg)
标签:__,name,python,send,msg,鸭子,类型,class,cls 来源: https://www.cnblogs.com/fmg0224/p/16343758.html