看得出来,FuglyHack可以为您的示例效劳,但ICantPromise还有其他方面:
orig_spam = spam.func_closure[0].cell_contents
编辑:对于多次装饰的函数/方法,以及使用更复杂的装饰器,您可以尝试使用以下代码。它依赖于这样一个事实,即修饰函数的名称与原始函数的名称不同。
def search_for_orig(decorated, orig_name):
for obj in (c.cell_contents for c in decorated.__closure__):
if hasattr(obj, "__name__") and obj.__name__ == orig_name:
return obj
if hasattr(obj, "__closure__") and obj.__closure__:
found = search_for_orig(obj, orig_name)
if found:
return found
return None
>>> search_for_orig(spam, "spam")
<function spam at 0x027ACD70>
虽然这不是傻瓜。如果从装饰器返回的函数名称与装饰器相同,则它将失败。hasattr()检查的顺序也是一种试探法,在任何情况下都有装饰链返回错误的结果。
_original,则最好将装饰器注释掉。