我想以编程方式将装饰器应用于类的所有方法。条件是如果某个装饰器已经存在,则跳过将装饰器添加到该方法。我有类似这段代码的代码,但我无法弄清楚 API 可以告诉我该方法上可能已经存在哪些其他装饰器。就我而言,我想跳过为某些带有装饰器的方法添加装饰cacheable器non_cacheabledef cacheable(): def decorate(cls): for name, fn in inspect.getmembers(cls, inspect.ismethod): setattr(cls, name, decorator(fn)) return cls return decorate@cacheableclass C(object): @not_cacheable def method_1(self): pass def method_2(self, x): pass ...
1 回答
![?](http://img1.sycdn.imooc.com/533e4d470001a00a02000200-100-100.jpg)
红糖糍粑
TA贡献1815条经验 获得超6个赞
尝试添加一个属性:
def not_cachable(func): func._cache = False return func
然后检查装饰器中的属性cacheable
。
这就是标准库中许多函数的工作原理,例如@abstractmethod
.
添加回答
举报
0/150
提交
取消