内省在方法上获取装饰器名称? [英] Introspection to get decorator names on a method?

查看:37
本文介绍了内省在方法上获取装饰器名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何获取方法上所有装饰器的名称。我已经可以获取方法名称和文档字符串,但是无法弄清楚如何获取装饰器列表。

I am trying to figure out how to get the names of all decorators on a method. I can already get the method name and docstring, but cannot figure out how to get a list of decorators.

推荐答案

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

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

然后您可以通过以下方式注册装饰器:

then you could register the decorators this way:

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 wrapper

decos = here = many

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

foo=Foo()

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

Here we access the tuple of decorators:

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

这里我们只打印装饰器的名称:

Here we print just the names of the decorators:

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

这篇关于内省在方法上获取装饰器名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆