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()
标签:__,name,lib,python,self,module,folder,动态,加载 From: https://www.cnblogs.com/shunguo/p/18107322