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

如何用父类方法装饰子类方法并保留类设计结构?

问题:使用父类方法装饰子类方法的实现方案

是否可以使用父类方法提取通用代码来装饰子类方法,同时保留类的设计与结构?

现有代码

class Parent:

    def general_create(self, create_child_func):
        def wrapper(*args, **kwargs):
            print("Some general actions before")
            result = create_child_func(*args, **kwargs)
            print("Some general actions after")
            return result
        return wrapper


class A(Parent):
    def create(self):
        print("Сreate actions for class A")
        return "Result A"


class B(Parent):
    def create(self):
        print("Сreate actions for class B")
        return "Result B"

尝试的错误写法

class Child(Parent):

@Parent.general_create # or @super().general_create
def create(self):
    print("Сreate actions for class Child")
    return "Result Child"

解决方案

你之前的写法报错原因很明确:

  • @Parent.general_create直接调用实例方法,但此时没有Parent实例,实例方法必须绑定到实例才能执行;
  • @super().general_create也不可行,super()只能在类的实例方法或类方法内部使用,类定义阶段无法直接调用。

下面提供两种可行的实现方式:

方式一:将父类装饰器改为静态方法

把general_create改为静态方法,无需实例即可直接作为装饰器使用:

class Parent:
    @staticmethod
    def general_create(create_child_func):
        def wrapper(*args, **kwargs):
            print("Some general actions before")
            result = create_child_func(*args, **kwargs)
            print("Some general actions after")
            return result
        return wrapper

class Child(Parent):
    @Parent.general_create
    def create(self):
        print("Сreate actions for class Child")
        return "Result Child"

# 测试验证
c = Child()
print(c.create())

方式二:父类初始化时动态装饰子类方法

在父类的__init__方法中,动态对子类的create方法进行装饰,既保留类结构,又能复用通用逻辑:

class Parent:
    def general_create(self, create_child_func):
        def wrapper(*args, **kwargs):
            print("Some general actions before")
            result = create_child_func(*args, **kwargs)
            print("Some general actions after")
            return result
        return wrapper

    def __init__(self):
        # 检查子类是否有create方法,存在则装饰
        if hasattr(self, 'create'):
            self.create = self.general_create(self.create)

class Child(Parent):
    def create(self):
        print("Сreate actions for class Child")
        return "Result Child"

# 测试验证
c = Child()
print(c.create())

这两种方式都能实现用父类的通用逻辑包装子类方法,同时完全保留原有类的设计与结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:01:24