我想以编程方式将装饰器应用于类的所有方法。条件是如果某个装饰器已经存在,则跳过将装饰器添加到该方法。
我有类似这段代码的代码,但我无法弄清楚 API 可以告诉我该方法上可能已经存在哪些其他装饰器。就我而言,我想跳过为某些带有装饰器的方法添加装饰cacheable器non_cacheable
def cacheable():
def decorate(cls):
for name, fn in inspect.getmembers(cls, inspect.ismethod):
setattr(cls, name, decorator(fn))
return cls
return decorate
@cacheable
class C(object):
@not_cacheable
def method_1(self): pass
def method_2(self, x): pass
...
红糖糍粑
相关分类