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

菲利普·斯蒂芬

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

在同一个班级中这样做可以正常工作:

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在函数内调用而不是将它包装在装饰器中。但是有没有办法让它发挥作用?

里卡多·布科

您只需要使用父类的名称:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章