python動態載入(三)

朵朵奇fa發表於2024-03-31
class TestInstance:
    def __init__(self):
        # 初始化庫字典,存放找到的庫
        self.lib = Proxy()  # 使用一個代理物件來模擬層級結構

        # 載入庫,這裡只是模擬,實際中需要匯入庫模組
        self._load_libs()

    def _load_libs(self):
        # 載入projectlib
        self._load_lib_folder()
        # 載入commonlib,如果projectlib中沒有找到對應的庫,這裡會作為後備
        self._load_lib_folder()

    def _load_lib_folder(self, folder_name):
        import os
        import importlib

        # 獲取庫資料夾的絕對路徑
        lib_folder_path = os.path.join(os.path.dirname(__file__), folder_name)

        # 遍歷庫資料夾中的所有檔案
        for filename in os.listdir(lib_folder_path):
            if filename.endswith('.py') and filename != '__init__.py':
                # 移除副檔名,得到庫名
                lib_module_name = filename[:-3]
                # 使用絕對匯入載入庫模組
                module = importlib.import_module(f'{folder_name}.{lib_module_name}')
                # 將庫模組新增到lib代理物件的層級結構中
                setattr(self.lib, lib_module_name, module)

    # def _load_lib_folder(self, folder_name):
    #     import os
    #     import sys
    #     import importlib
    #
    #     # 獲取庫資料夾的絕對路徑
    #     lib_folder_path = os.path.join(os.path.dirname(__file__), folder_name)
    #
    #     # 遍歷庫資料夾中的所有檔案
    #     for filename in os.listdir(lib_folder_path):
    #         if filename.endswith('.py') and filename != '__init__.py':
    #             # 移除副檔名,得到庫名
    #             lib_module_name = filename[:-3]
    #             # 匯入庫模組
    #             module = importlib.import_module(f'.{folder_name}.{lib_module_name}', __name__)
    #             # 將庫模組新增到lib代理物件的層級結構中
    #             setattr(self.lib, lib_module_name, module)

            # 定義一個代理類,用於模擬屬性訪問


class Proxy:
    def __init__(self):
        self._parent = None

    def __getattr__(self, name):
        # 遞迴地向上查詢父物件,直到找到對應的屬性或達到根物件
        parent = self._parent
        while parent is not None:
            try:
                return getattr(parent, name)
            except AttributeError:
                parent = getattr(parent, '_parent', None)
        raise AttributeError(f"module '{name}' not found")

        # 其他測試例項相關的方法...


class MyTest(TestInstance):
    def test_greet(self):
        # 呼叫projectlib中的greet函式
        result = self.lib.libA.greet()
        print(result)  # 應該輸出: Hello from projectlib's libA!


if __name__ == '__main__':
    my_test = MyTest()
    my_test.test_greet()

  

相關文章