微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我试图在类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,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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。