You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自动为包含A实例列表的B类生成类A的对应扩展方法?

实现方案

方案1:类装饰器预生成代理方法(推荐)

该方案会在类定义阶段批量生成所有代理方法,完全兼容IDE自动补全,且自动保留原方法的文档字符串,适配绝大多数场景。
首先导入依赖:

from functools import wraps
import inspect

实现类装饰器:

def delegate_A_methods(attr_name="list_of_A"):
    def decorator(B_cls):
        # 遍历A类的所有用户自定义方法,过滤双下划线开头的魔法方法
        for method_name, method in inspect.getmembers(A, predicate=inspect.isfunction):
            if method_name.startswith("__"):
                continue
            
            # 生成B类的对应代理方法,用wraps复制原方法元信息(含文档字符串)
            @wraps(method)
            def proxy_method(self, *args, __method_name=method_name, **kwargs):
                # 可在此处添加统一前置逻辑
                # 批量调用所有A实例的对应方法
                result_list = []
                for a_instance in getattr(self, attr_name):
                    res = getattr(a_instance, __method_name)(*args, **kwargs)
                    result_list.append(res)
                # 可在此处添加统一后置逻辑
                return result_list
            
            # 将生成的代理方法绑定到B类
            setattr(B_cls, method_name, proxy_method)
        return B_cls
    return decorator

使用方法:给B类加上装饰器即可

@delegate_A_methods(attr_name="list_of_A")
class B:
    def __init__(self, n):
        self.list_of_A = [A() for _ in range(n)]
    
    # B类自有方法可正常编写,不会被代理方法覆盖
    def custom_func(self):
        pass

如果需要为单个方法配置独立的前置/后置逻辑,可以扩展装饰器支持钩子函数,示例如下:
在proxy_method的对应位置添加钩子调用:

# 前置钩子调用
before_hook = getattr(self, f"before_{__method_name}", None)
if callable(before_hook):
    before_hook(*args, **kwargs)

# 后置钩子调用
after_hook = getattr(self, f"after_{__method_name}", None)
if callable(after_hook):
    after_hook(result_list, *args, **kwargs)

之后只要在B类中定义before_func1/after_func1方法,就会自动在func1调用前后执行。


方案2:__getattr__懒加载实现

该方案只会在方法首次被调用时生成代理方法,内存占用更低,适合A类方法非常多且调用频率低的场景。

from functools import wraps

class B:
    def __init__(self, n):
        self.list_of_A = [A() for _ in range(n)]
    
    def __getattr__(self, method_name):
        # 校验A类是否存在对应可调用方法
        if hasattr(A, method_name) and callable(getattr(A, method_name)) and not method_name.startswith("__"):
            origin_method = getattr(A, method_name)
            @wraps(origin_method)
            def proxy_method(*args, **kwargs):
                # 前置逻辑
                result_list = []
                for a_instance in self.list_of_A:
                    res = getattr(a_instance, method_name)(*args, **kwargs)
                    result_list.append(res)
                # 后置逻辑
                return result_list
            # 缓存生成的方法,下次调用无需重复生成
            setattr(self, method_name, proxy_method)
            return proxy_method
        # 不存在对应方法时抛出标准异常
        raise AttributeError(f"'B' object has no attribute '{method_name}'")

该方案的缺点是未被调用过的方法不会出现在类的属性列表中,IDE自动补全不会生效。


内容的提问来源于stack exchange,提问作者lcb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 14:36:02