python - 使用从父类继承的方法作为子类方法的装饰器
问题描述
我正在尝试在类 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)
推荐阅读
- html - 使用引导程序的 div 之间的 Html css 空间
- sonarqube - 在 SonarQube 问题页面上,如何过滤出违反特定规则的行为?
- javascript - 如果我在两列中进行编辑,图像应该保持不变
- apache-spark - 将 spark 数据帧写入 hdfs 时的额外分隔符
- mysql - 尝试将列加入 key_column_usage
- c++ - 获取makefile以更改输出可执行文件名称
- android - 如何将 Mapbox 遥测添加到 android?
- angular - CucumberJS 场景大纲,创建步骤代码
- r - 使用特定值在 R 中设置子集的问题
- mysql - 为什么我无法使用 MySQL Workbench 连接到我的 MySQL 数据库?