【发布时间】:2020-12-20 17:29:06
【问题描述】:
我想创建一个类来继承其他地方,并使用装饰器将特定方法存储在属性中。
我尝试了以下装饰器
def filtermethod(f):
def wrapped(self, *args, **kwargs):
self.methods.append(f)
return f(self, *args, **kwargs)
return wrapped
并用
定义类class foo:
def __init__(self):
self.methods = []
def apply_filter(self, x):
for fun in self.methods:
x = fun(x)
return x
class foo2(foo):
@filtermethod
def method1(self, x):
return [i for i in x if i > 5]
@filtermethod
def method2(self, x):
return [i for i in x if i < 18]
并使用以下内容测试该类
foo2().apply_filter([1, 4, 1, 5, 73, 25, 7, 2, 26, 13, 46, 9])
并期望所有修饰函数都应用于参数,但我明白了
[1, 4, 1, 5, 73, 25, 7, 2, 26, 13, 46, 9]
而不是
[7,13,9]
基本上,我想将每个用@filtermethod 装饰的函数附加到属性self.methods,(与self.apply_filter 连续应用)但我根本做不到。
有什么线索吗?
【问题讨论】:
-
您将包装方法添加到
self.methods的唯一时间是您实际调用包装方法时 - 例如,method1或method2。
标签: python class inheritance decorator