问题
def log(func):
def wraper(*a, **kw):
return func(*a, **kw)
return wraper
@log
def f():
print 'f'
print locals()['f'] # - prints <function wraper at 0x00CBF3F0>.
How do you get the real f object (not decorator wrap)?
回答1:
You don't.1 Store it if you need to access it later.
def log(func):
def wrapper(*a, **kw):
return func(*a, **kw)
wrapper.func = func
return wrapper
@log
def f():
print 'f'
print f.func
1 You could mess with the closure, but I can't recommend it.
回答2:
The functools module also provides a wraps
decorator which makes sure that the wrapped function looks more like the real function: correct name, module, and docstring, for example.
回答3:
If you're running python 3.2 or above, and you use functools.wraps then you will find the wrapped function on the __wrapped__
attribute:
from functools import wraps
def log(func):
@wraps(func)
def wrapper(*a, **kw):
return func(*a, **kw)
return wrapper
@log
def f():
print 'f'
print f.__wrapped__
functools.wraps
is a convenience function for decorating a decorated function with the function that does all the work, including adding this attribute functools.update_wrapper.
来源:https://stackoverflow.com/questions/2413271/get-decorated-function-object-by-string-name