# testInstance.py import importlib import sys class TestInstance: def __init__(self, projectName): self.projectName = projectName self.lib = self.load_libraries() def load_libraries(self): # Import the configuration module import libconfig libraries = {} # Append the library paths to sys.path sys.path.append("library/commonlib") sys.path.append("library/projectlib") # Load libraries in the specified order for lib_name in libconfig.libraries_order: # Import the library module module = importlib.import_module(lib_name) # Add the module's attributes to the libraries dict libraries.update({attr_name: getattr(module, attr_name) for attr_name in dir(module) if not attr_name.startswith('_')}) # Create a namespace-like object to hold the classes/functions from all libraries class LibraryNamespace: def __getattr__(self, item): # First check if the attribute exists in the current project's libraries if item in libraries: return libraries[item] # If not found, check commonlib commonlib_module = importlib.import_module(f"commonlib.{item}") return getattr(commonlib_module, item) # Return the namespace object return LibraryNamespace() # Example usage if __name__ == '__main__': # Assume the current project name is "projectlib" projectName = "projectlib" test = TestInstance(projectName) # Call greet function from libA without explicitly checking for its existence # The framework handles the fallback logic if the function is not found in the project's library print(test.libA.greet("World"))
在这个修改后的代码中,load_libraries
方法现在将所有库的属性合并到一个字典中,而LibraryNamespace
类则覆盖了__getattr__
方法以处理属性的动态查找。当尝试访问test.libA.greet
时,如果greet
函数在项目的库中不存在,__getattr__
方法会尝试从commonlib
库中导入libA
模块并获取greet
函数。
这意味着,脚本中不需要进行任何显式的检查来确定函数的位置。当调用test.libA.greet("World")
时,如果函数在项目库中不存在,框架将自动回退到commonlib
库并尝试调用该函数。
请确保libconfig.libraries_order
列表中的库加载顺序符合你的要求,即项目库应该在commonlib
之前,这样项目库中的函数将优先被调用。如果项目库中没有找到函数,那么commonlib
中的函数将被调用。