使用从父 class 继承的方法作为子 classes 方法的装饰器

Use inherited method from parent class as decorator on child classes method

我正在尝试在 class A 中设置一个方法,该方法可以在子 class B 中用作方法的装饰器。我想根据一些实例属性将参数映射到这些函数。

在同一个 class 中执行此操作效果很好:

class Class:
    def __init__(self):
        self.mapper = "mapped "

    def map_arg(func):
        def mapped_func(self, unmapped_value):
            mapped_value = self.mapper + unmapped_value
            return func(self, mapped_value)
        return mapped_func

    @map_arg
    def func(self, mapped_value):
        print(mapped_value)

obj = Class()
obj.func("value")

打印 mapped value。但是当我尝试继承装饰器时,它会抛出 NameError

class ParentClass:
    def map_arg(func):
        def mapped_func(self, unmapped_value):
            mapped_value = self.mapper + unmapped_value
            return func(self, mapped_value)
        return mapped_func

class ChildClass(ParentClass):
    def __init__(self):
        self.mapper = "mapped "

    @map_arg
    def func(self, mapped_value):
        print(mapped_value)

obj = ChildClass()
obj.func("value")
Traceback (most recent call last):
  File "/tmp/decorator.py", line 43, in <module>
    class ChildClass(ParentClass):
  File "/tmp/decorator.py", line 47, in ChildClass
    @map_arg
NameError: name 'map_arg' is not defined

我也试过使用 @super().map_arg,但这是一个语法错误。我想在函数中调用 self.map_arg 而不是将其包装在装饰器中更容易。但是有办法让它发挥作用吗?

你只需要使用你的名字 parent class:

class ChildClass(ParentClass):
    def __init__(self):
        self.mapper = "mapped "
    @ParentClass.map_arg
    def func(self, mapped_value):
        print(mapped_value)