内省在方法上获取装饰器名称?

内省在方法上获取装饰器名称?,第1张

内省在方法上获取装饰名称

如果可以更改从中调用装饰器的方式

class Foo(object):    @many    @decorators    @here    def bar(self):        pass

class Foo(object):    @register(many,decos,here)    def bar(self):        pass

那么您可以通过以下方式注册装饰器:

def register(*decorators):    def register_wrapper(func):        for deco in decorators[::-1]: func=deco(func)        func._decorators=decorators     return func    return register_wrapper

例如:

def many(f):    def wrapper(*args,**kwds):        return f(*args,**kwds)    return wrapperdecos = here = manyclass Foo(object):    @register(many,decos,here)    def bar(self):        passfoo=Foo()

在这里,我们访问装饰器的元组:

print(foo.bar._decorators)# (<function many at 0xb76d9d14>, <function decos at 0xb76d9d4c>, <function here at 0xb76d9d84>)

在这里,我们仅打印装饰器的名称:

print([d.func_name for d in foo.bar._decorators])# ['many', 'decos', 'here']


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5639610.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存