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

如何在Python子类B中自动为继承自A的方法添加装饰器

解决方案

错误原因

你遇到的TypeError是因为_preCheck被定义为类的实例方法,当通过self._preCheck调用时,Python会自动把self作为第一个参数传入,但_preCheck只声明了一个func参数,导致参数数量不匹配。

修正后的完整实现

from functools import wraps

class A(object):
    def __init__(self, name):
        self.name = name
    
    def add(self, a, b):
        return a + b

class B(A):
    def __init__(self, name, foo):
        super().__init__(name)
        self.foo = foo
        self._auto_decorate_parent_methods()
        
    @staticmethod
    def _preCheck(func):
        @wraps(func)
        def wrapper(self, *args, **kwargs):
            print("preProcess", self.name)
            return func(self, *args, **kwargs)
        return wrapper
    
    def _auto_decorate_parent_methods(self):
        # 遍历父类A的所有公开属性
        for attr_name in dir(A):
            # 跳过特殊方法(如__init__、__str__等)
            if attr_name.startswith('__') and attr_name.endswith('__'):
                continue
            attr = getattr(A, attr_name)
            # 只处理可调用的方法
            if callable(attr):
                decorated = self._preCheck(attr)
                setattr(self, attr_name, decorated)
                
    @_preCheck
    def double(self, i):
        return i * 2
    
b = B('myInst', 'bar')
print(b.double(5))
print(b.add(1,2))

关键修改点

  1. 将_preCheck改为静态方法:添加@staticmethod装饰器,避免调用时自动传入self参数,解决参数不匹配问题。
  2. 优化方法筛选逻辑:用dir(A)遍历父类公开属性,跳过特殊方法,只装饰普通可调用方法,避免误装饰内置方法。
  3. 封装装饰逻辑:把自动装饰的代码放到单独的_auto_decorate_parent_methods方法中,让__init__逻辑更清晰。

运行后输出:

preProcess myInst
10
preProcess myInst
3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 23:50:42