我理解python中函数的装饰器(我可能错了)的方法是,它们应该添加副作用并修改函数的返回值。现在装饰器被添加到要装饰的函数的函数定义之上或通过赋值。这是一个小例子:
def print_args_decor(function):
def wrapper(*args, **kwargs):
print 'Arguments:', args, kwargs # Added side-effect
return function(*args, **kwargs)*5 # Modified return value
return wrapper
@print_args_decor
def do_stuff(strg, n=10):
"""Repeats strg a few times."""
return strg * n
new_decorated_func = print_args_decor(do_stuff) # Decoration by assignment
print do_stuff('a', 2) # Output: aaaaaaaaaa
现在,如何将装饰器附加到其他地方定义的函数,理想情况下保留原始函数的名称和docstring (如functools.wraps
那样)?例如,我正在从Python的数学模块中导入sqrt()
函数,并且想要装饰它,我该怎么做呢?
from functools import wraps
from math import sqrt
def print_args_decor(function):
@wraps(function)
def wrapper(*args, **kwargs):
print 'Arguments:', args, kwargs # Added side-effect
return function(*args, **kwargs)*5 # Modified return value
return wrapper
# Decorate the sqrt() function from math module somehow
@print_args_decor #???
sqrt #???
print sqrt(9)
# Output:
# Arguments: ([9],) {}
# 15 # <--- sqrt(9)*5
如何在类之后装饰类中的方法?如何自己装饰课程?