猿问

获取所有函数装饰器的名称

我想以编程方式将装饰器应用于类的所有方法。条件是如果某个装饰器已经存在,则跳过将装饰器添加到该方法。


我有类似这段代码的代码,但我无法弄清楚 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

    ...


陪伴而非守候
浏览 114回答 1
1回答

红糖糍粑

尝试添加一个属性:def not_cachable(func):     func._cache = False     return func然后检查装饰器中的属性cacheable。这就是标准库中许多函数的工作原理,例如@abstractmethod.
随时随地看视频慕课网APP

相关分类

Python
我要回答