【问题标题】:Use inherited method from parent class as decorator on child classes method使用从父类继承的方法作为子类方法的装饰器
【发布时间】:2021-02-12 00:44:31
【问题描述】:

我正在尝试在类 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 比将其包装在装饰器中更容易。但是有办法让它发挥作用吗?

【问题讨论】:

    标签: python python-3.x inheritance decorator


    【解决方案1】:

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

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

    【讨论】:

    • 嗯,事后看来这很明显。谢谢!
    猜你喜欢
    • 2019-11-27
    • 2021-02-21
    • 2012-11-14
    • 2014-09-06
    • 2017-07-05
    • 2020-12-28
    • 2018-07-10
    • 1970-01-01
    • 2018-01-16
    相关资源
    最近更新 更多