【发布时间】: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