1. 程式人生 > 其它 >importlib模組與基於中介軟體實現的程式設計思想

importlib模組與基於中介軟體實現的程式設計思想

importlib 模組介紹

我們平時匯入 python 模組一般是使用 from .. import .. 的匯入語句

from django.shortcuts import HttpResponse

現在我來介紹一種新的匯入模組方法。

使用 importlib 可以根據模組字串路徑來匯入模組。

使用:

import importlib


model_path = 'notify.email'
model = importlib.import_module(model_path)  # 可以得到模組物件,之間 model.類名 可以獲取該模組中的類


print(model)  # <module 'notify.email' from 'E:\\\\notify\\email.py'>

obj = model.Email()  # 例項化模組中的類物件
obj.send('很nice')  # 呼叫類中的方法

基於中介軟體實現的程式設計思想

檔案路徑:

--notify : 是存放了多個功能模組的包

--settings.py : 配置檔案,裡面的 MIDDLEWARE 列表存放 notify 中部分類的字串路徑

--start.py : 啟動檔案

notify

''' __init__.py(核心)'''

import settings
import importlib


def send_all(content):
    # 迴圈 settings 檔案中的登錄檔
    for path_str in settings.MIDDLEWARE:
        # 1、把模組路徑和類名分割出來
        model_path, class_name = path_str.rsplit('.', maxsplit=1)
        # 2、使用 importlib 模組來匯入列表中的模組
        model = importlib.import_module(model_path)
        # 3、用反射機制來取出模組中類的地址
        cls = getattr(model, class_name)
        # 4、例項化物件並呼叫各自的send方法傳送
        obj = cls()
        obj.send(content)  # 鴨子型別(多型)
'''wechat.py'''
class Wechat:
    def __init__(self):
        pass

    def send(self, content):
        print(f'微信傳送:{content}')


'''qq.py'''
class QQ:
    def __init__(self):
        pass

    def send(self, content):
        print(f'QQ傳送:{content}')


'''eamil.py'''
class Email:
    def __init__(self):
        pass

    def send(self, content):
        print(f'email傳送:{content}')

settings.py:

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

start.py:

import notify


while True:
    content = input('請書寫傳送通告:')

    notify.send_all(content)

執行效果

如果需要新增其它通訊工具

  • 在 notify 中新增該通訊工具的模組,書寫類,類中必須有 send() 方法(多型),鴨子型別
  • 在 settings.py 中新增該模組的字串路徑

如果不想呼叫哪個模組,直接在 settings.py 中註釋掉它的路徑

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