如何在Python中实现类似JS的类实例存储到对象的模式?
Python 中对应 JS 类实例存储模式的实现方案
背景:JavaScript 中的类实例存储模式
在 JavaScript 中,可以把包含方法的类实例存储到对象中,方便其他模块调用其方法,示例代码如下:
const myFunctionClass = function(){ this.propertyFunction = function myFunc(){ console.log('hi') } } const initFunctionClass = new myFunctionClass() const obj = {} obj["myFunctionClass"] = initFunctionClass console.log(obj) /* Output { myFunctionClass: myFunctionClass { propertyFunction: [Function: myFunc] } } */
这段代码的核心是将实例化后的类存入对象,实现实例的集中管理与跨模块调用。
问题:Python 中是否有类似模式?
用户需要实现的是:动态导入指定路径下文件中的类,实例化后做单元测试验证并存储,现有 Python 代码片段如下:
import os from os import walk class Core: def load_adapters(self, path): api_adapters = {} for folder in os.scandir(path): api_adapter = folder.name file = next(walk(path + '/' + folder.name), (None, None, []))[2] # [] if no file # I want to import each found file, which will contain a class, # then initialize the classes and validate them with unit testing from api_adapters[api_adapter][file] import api_adapter # this code relates to the question return api_adapters
解答:Python 的对应实现思路
Python 中完全可以实现类似逻辑,核心是动态导入模块+实例化类+将实例存入字典,和 JS 的思路本质一致,只是语法不同。
关键步骤说明
- 动态导入模块:使用 Python 内置的
importlib库实现动态导入,替代静态import语句 - 路径与模块名转换:将文件路径转换为符合 Python 规范的模块名(避免特殊字符,采用
文件夹名.文件名的格式) - 实例化类:约定类名与文件名的对应规则(比如文件名小写,类名首字母大写),通过反射获取类并实例化
- 存储与验证:将实例存入字典集中管理,同时插入单元测试逻辑验证实例有效性
修改后的代码示例
import os import importlib import sys from typing import Dict, Type class Core: def load_adapters(self, path: str) -> Dict[str, object]: api_adapters = {} abs_path = os.path.abspath(path) # 将目标路径加入Python模块搜索路径,确保能找到要导入的模块 if abs_path not in sys.path: sys.path.append(abs_path) for folder in os.scandir(abs_path): if not folder.is_dir(): continue folder_name = folder.name # 遍历文件夹下的所有.py文件 for _, _, files in os.walk(folder.path): for file in files: if not file.endswith('.py') or file == '__init__.py': continue # 构建模块名:文件夹名.文件名(去掉.py后缀) module_name = f"{folder_name}.{os.path.splitext(file)[0]}" try: # 动态导入模块 module = importlib.import_module(module_name) # 约定类名与文件名首字母大写一致(比如adapter.py对应Adapter类) class_name = os.path.splitext(file)[0].capitalize() if hasattr(module, class_name): adapter_class: Type = getattr(module, class_name) # 实例化类 adapter_instance = adapter_class() # 执行单元测试验证,验证不通过则跳过存储 if self.validate_adapter(adapter_instance): api_adapters[module_name] = adapter_instance except Exception as e: print(f"导入模块 {module_name} 失败: {str(e)}") return api_adapters # 单元测试验证方法示例,可根据实际需求扩展 def validate_adapter(self, adapter_instance: object) -> bool: # 示例:检查实例是否包含指定方法,且调用后返回预期值 if not hasattr(adapter_instance, 'test_method'): return False try: result = adapter_instance.test_method() return result == "expected_valid_result" except Exception: return False
代码说明
- 动态导入逻辑:通过
importlib.import_module实现模块的动态导入,适配任意路径下的多个文件 - 路径处理:将目标路径加入
sys.path,确保 Python 能识别该路径下的模块;模块名严格遵循 Python 命名规范 - 实例化与存储:通过反射
getattr获取类并实例化,验证通过后将实例存入字典,实现集中管理 - 验证逻辑:
validate_adapter方法提供了单元测试的基础框架,可根据实际业务需求添加更多校验规则
内容的提问来源于stack exchange,提问作者Dshiz
相关产品推荐
相关产品推荐

