模块功能导入的重要思想

发布时间 2023-10-23 11:37:08作者: PiggThird

前期我们需要准备一个notify文件夹、settings.py和start.py
notify文件夹下面放你想要实现的功能,当作一个包来使用

一个简单的小案例

"""
简单实现多软件发消息
notify文件夹
  __init___.py
  wechat.py
  qq.py
  email.py
  msg.py

settings.py

start.py
"""

notify文件下的py文件放的内容

# __init__.py
import settings
import importlib


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)

# wechat.py
class Wechat(object):
    def __init__(self):
        pass

    def send(self, content):
        print('微信发送消息:%s' % content)

# email
class Email(object):
    def __init__(self):
        pass

    def send(self, content):
        print('邮箱发送消息:%s' % content)

# qq
class QQ(object):
    def __init__(self):
        pass

    def send(self, content):
        print('QQ发送消息:%s' % content)

# msg
class Msg(object):
    def __init__(self):
        pass

    def send(self, content):
        print('短信发送消息:%s' % content)

settings.py

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

start.py

import notify

notify.send_all('大家好!')

执行结果

微信发送消息:大家好!
QQ发送消息:大家好!
邮箱发送消息:大家好!
短信发送消息:大家好!

重要思想!!!

当我们想要关闭某些功能或者开启某些功能 直接去settings.py文件中 注释 或者 取消注释 字符串即可实现