【问题标题】:Is there a way to get the function a decorator has wrapped?有没有办法获得装饰器包装的功能?
【发布时间】:2009-10-09 17:51:55
【问题描述】:
假设我有
@someDecorator
def func():
'''this function does something'''
print 1
现在,对象func 是someDecorator 的一个实例。有什么方法可以访问它所拥有的功能,例如func.getInnerFunction()。
例如,如果我需要检索func() 的文档字符串。
【问题讨论】:
标签:
python
function
nested
decorator
【解决方案2】:
SilentGhost 和 sri 对于如何处理这个问题有部分答案。但一般的答案是否定的:没有办法从装饰函数中获取“包装”函数,因为没有要求装饰器首先包装函数。它很可能返回了一个完全不相关的函数,并且对您的原始函数的任何引用都可能已经被垃圾回收了。
【解决方案3】:
您是否正在寻找类似的东西?
>>> def dec(f):
def inner():
print(f.__doc__)
return inner
>>> @dec
def test():
"""abc"""
print(1)
>>> test()
abc
您将函数显式传递给装饰器,当然您可以访问它。
【解决方案4】:
您可以将包装函数附加到内部函数
In [1]: def wrapper(f):
...: def inner():
...: print "inner"
...: inner._orig = f
...: return inner
...:
In [2]: @wrapper
...: def foo():
...: print "foo"
...:
...:
In [3]: foo()
inner
In [4]: foo._orig()
foo