4. python 基于配置文件的编程思想


对象版

文件结构

notify 里定义的是各种通知的方法
main 程序执行的入口
settings 配置文件

email.py

class Email(object):
    def __init__(self):
        pass
    def send(self,content):
        print('email消息: {}'.format(content))

qq.py

class QQ(object):
    def __init__(self):
        pass
    def send(self,content):
        print('QQ消息: {}'.format(content))

wechat.py

class Wechat(object):
    def __init__(self):
        pass
    def send(self,content):
        print('微信消息: {}'.format(content))

notify.init.py

from method1 import settings
import importlib


def send_all(content):
    for path_str in settings.NOTIFY_LIST:
        # 模块名,类名
        modules_path, class_name = path_str.rsplit('.', maxsplit=1)
        # print(modules_path,class_name)
        # 1. 利用字符串导入模块
        module = importlib.import_module(modules_path)  # from notify import email

        # 2. 利用反射获取类名
        cls = getattr(module,class_name)
        # 3. 生产类对象
        obj=cls()
        # 4. 利用鸭子类型直接调用send方法
        obj.send(content)

settings.py

NOTIFY_LIST=[
    'notify.qq.QQ',
    'notify.email.Email',
    'notify.wechat.Wechat',
]

main.py

import notify
notify.send_all('hello')

函数版

文件结构

notify.py

def weixin(context):
    print('微信发送: {}'.format(context))

def qq(context):
    print('QQ发送: {}'.format(context))

def email(context):
    print('email发送: {}'.format(context))

send=[
    'weixin',
    'qq',
    'email'
]

main.py

import notify
def send_all(context):
    #
    for func in notify.send:
        func_file = 'notify'
        # 拼接出函数名和函数内容
        func_name = "{}.{}('{}')".format(func_file,func,context)
        eval(func_name)


send_all('快放假了')