如何获取使用@decorator2 修饰的给定类 A 的所有方法?
class A():
def method_a(self):
pass
@decorator1
def method_b(self, b):
pass
@decorator2
def method_c(self, t=5):
pass
最佳答案
方法一:基本注册装饰器
我已经在这里回答了这个问题:Calling functions by array index in Python =)
方法二:源码解析
如果您无法控制 类(class)定义,这是您想假设的一种解释,这是 不可能 (没有代码读取反射),因为例如装饰器可能是一个无操作装饰器(就像我链接的例子中那样),它只返回未修改的函数。 (尽管如此,如果您允许自己包装/重新定义装饰器,请参阅 方法 3:将装饰器转换为“自我感知” ,那么您将找到一个优雅的解决方案)
这是一个可怕的黑客,但你可以使用 inspect
模块读取源代码本身,并解析它。这在交互式解释器中不起作用,因为检查模块将拒绝以交互模式提供源代码。但是,下面是概念证明。
#!/usr/bin/python3
import inspect
def deco(func):
return func
def deco2():
def wrapper(func):
pass
return wrapper
class Test(object):
@deco
def method(self):
pass
@deco2()
def method2(self):
pass
def methodsWithDecorator(cls, decoratorName):
sourcelines = inspect.getsourcelines(cls)[0]
for i,line in enumerate(sourcelines):
line = line.strip()
if line.split('(')[0].strip() == '@'+decoratorName: # leaving a bit out
nextLine = sourcelines[i+1]
name = nextLine.split('def')[1].split('(')[0].strip()
yield(name)
它有效!:
>>> print(list( methodsWithDecorator(Test, 'deco') ))
['method']
请注意,必须注意解析和 python 语法,例如
@deco
和 @deco(...
是有效的结果,但 @deco2
如果我们只是要求 'deco'
,则不应退还.我们注意到,根据 http://docs.python.org/reference/compound_stmts.html 处的官方 python 语法。装饰器如下:decorator ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
不必处理像
@(deco)
这样的案例,我们松了一口气。 .但是请注意,如果您有非常复杂的装饰器,例如 @getDecorator(...)
,这仍然没有真正帮助您。 ,例如def getDecorator():
return deco
因此,这种你能做的最好的代码解析策略无法检测到这样的情况。但是,如果您正在使用此方法,那么您真正追求的是定义中方法顶部的内容,在本例中为
getDecorator
.根据规范,具有
@foo1.bar2.baz3(...)
也是有效的。作为装饰者。您可以扩展此方法以使用它。您也可以扩展此方法以返回 <function object ...>
而不是函数的名称,需要付出很多努力。然而,这种方法是hackish和可怕的。方法 3:将装饰器转换为“自我意识”
如果您无法控制 装饰定义(这是您想要的另一种解释),然后所有这些问题都会消失,因为您可以控制装饰器的应用方式。因此,您可以通过包装它来修 retrofit 饰器,以创建自己的装饰器,并使用它来装饰您的函数。让我再说一遍:你可以制作一个装饰器来装饰你无法控制的装饰器,“启发”它,在我们的例子中,这让它做它之前做的事情,但也附加一个
.decorator
它返回的可调用对象的元数据属性,允许您跟踪“这个函数是否被装饰过?让我们检查一下 function.decorator!”。和 然后 你可以遍历类的方法,然后检查装饰器是否有合适的 .decorator
属性(property)! =) 如此处所示:def makeRegisteringDecorator(foreignDecorator):
"""
Returns a copy of foreignDecorator, which is identical in every
way(*), except also appends a .decorator property to the callable it
spits out.
"""
def newDecorator(func):
# Call to newDecorator(method)
# Exactly like old decorator, but output keeps track of what decorated it
R = foreignDecorator(func) # apply foreignDecorator, like call to foreignDecorator(method) would have done
R.decorator = newDecorator # keep track of decorator
#R.original = func # might as well keep track of everything!
return R
newDecorator.__name__ = foreignDecorator.__name__
newDecorator.__doc__ = foreignDecorator.__doc__
# (*)We can be somewhat "hygienic", but newDecorator still isn't signature-preserving, i.e. you will not be able to get a runtime list of parameters. For that, you need hackish libraries...but in this case, the only argument is func, so it's not a big issue
return newDecorator
为
@decorator
演示:deco = makeRegisteringDecorator(deco)
class Test2(object):
@deco
def method(self):
pass
@deco2()
def method2(self):
pass
def methodsWithDecorator(cls, decorator):
"""
Returns all methods in CLS with DECORATOR as the
outermost decorator.
DECORATOR must be a "registering decorator"; one
can make any decorator "registering" via the
makeRegisteringDecorator function.
"""
for maybeDecorated in cls.__dict__.values():
if hasattr(maybeDecorated, 'decorator'):
if maybeDecorated.decorator == decorator:
print(maybeDecorated)
yield maybeDecorated
它有效!:
>>> print(list( methodsWithDecorator(Test2, deco) ))
[<function method at 0x7d62f8>]
但是,“注册装饰器”必须是 最外层装饰器 , 否则
.decorator
属性注释将丢失。例如在火车上@decoOutermost
@deco
@decoInnermost
def func(): ...
您只能看到
decoOutermost
的元数据暴露,除非我们保留对“更内部”包装器的引用。旁注:上述方法也可以建立一个
.decorator
跟踪 应用的装饰器和输入函数以及装饰器工厂参数的整个堆栈 . =) 例如,如果您考虑注释掉的行 R.original = func
,使用这样的方法来跟踪所有包装层是可行的。如果我写了一个装饰器库,这就是我个人会做的事情,因为它允许深入内省(introspection)。@foo
之间也有区别和 @bar(...)
.虽然它们都是规范中定义的“装饰器表达式”,但请注意 foo
是装饰器,而 bar(...)
返回一个动态创建的装饰器,然后应用它。因此你需要一个单独的函数 makeRegisteringDecoratorFactory
,有点像 makeRegisteringDecorator
但更多元:def makeRegisteringDecoratorFactory(foreignDecoratorFactory):
def newDecoratorFactory(*args, **kw):
oldGeneratedDecorator = foreignDecoratorFactory(*args, **kw)
def newGeneratedDecorator(func):
modifiedFunc = oldGeneratedDecorator(func)
modifiedFunc.decorator = newDecoratorFactory # keep track of decorator
return modifiedFunc
return newGeneratedDecorator
newDecoratorFactory.__name__ = foreignDecoratorFactory.__name__
newDecoratorFactory.__doc__ = foreignDecoratorFactory.__doc__
return newDecoratorFactory
为
@decorator(...)
演示:def deco2():
def simpleDeco(func):
return func
return simpleDeco
deco2 = makeRegisteringDecoratorFactory(deco2)
print(deco2.__name__)
# RESULT: 'deco2'
@deco2()
def f():
pass
这个生成器工厂包装器也适用:
>>> print(f.decorator)
<function deco2 at 0x6a6408>
奖金让我们甚至用方法 #3 尝试以下操作:
def getDecorator(): # let's do some dispatching!
return deco
class Test3(object):
@getDecorator()
def method(self):
pass
@deco2()
def method2(self):
pass
结果:
>>> print(list( methodsWithDecorator(Test3, deco) ))
[<function method at 0x7d62f8>]
如您所见,与 method2 不同,@deco 被正确识别,即使它从未明确写入类中。与 method2 不同,如果该方法在运行时添加(手动,通过元类等)或继承,这也将起作用。
请注意,您也可以装饰一个类,因此如果您“启发”一个既用于装饰方法又用于装饰类的装饰器,然后在要分析的类的主体中编写一个类,那么
methodsWithDecorator
将返回装饰类以及装饰方法。人们可以将其视为一项功能,但您可以通过检查装饰器的参数(即 .original
)轻松编写逻辑以忽略这些功能。 , 以实现所需的语义。
关于python - 如何使用给定的装饰器获取python类的所有方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5910703/