装饰器
装饰器(Decorators)是 Python 的一个重要部分。简单地说:他们是修改其他函数的功能的函数。
普通装饰器
个人理解普通装饰器和直接调用函数没什么区别,就是相当于函数的调用。
def test1(x):
return x ** 2
def test2(x):
return x * 3 + x / 2
test1(6)
test2(8)
def func(f):
def fNew(x):
print(f.__name__)
return f(x)
return fNew
f = func(test1)
print(f(4))
f = func(test2)
print(f(4))
@func
def test3(x):
return x * 10 * (x + 1)
rst = test3(6)
print(rst)
from functools import wraps
def a_new_decorator(a_func):
@wraps(a_func)
def wrapTheFunction():
print("I am doing some boring work before executing a_func()")
a_func()
print("I am doing some boring work after executing a_func()")
return wrapTheFunction
@a_new_decorator
def a_function_requiring_decoration():
"""Hey yo! Decorate me!"""
print("I am the function which needs some decoration to "
"remove my foul smell")
print(a_function_requiring_decoration.__name__)
a_function_requiring_decoration()
运行结果:
大家可以自己运行一下。
装饰器带参数
类装饰器
类方法装饰器
后面的几个内容,在这篇博文里面都已经有具体的代码了,我这里就不再贴代码了。
感兴趣的小伙伴可以去看看。
划重点:
本文中链接都指向同一篇博文,所以点击哪一个链接都可以噢。