装饰器:
装饰器:用来修改函数功能的函数
- 可以在不改变原函数的基础上添加功能
实现装饰器的方法:从函数中返回函数,将原函数作为一个参数传给另一个函数
代码:装饰器pro_print在函数执行前输出提示"welcome to class"
def pro_print(fun): # 装饰器函数
def wrapper(*args,**kwargs): # 接收各种类型的不定长参数
print("welcome to class")
fun()
return wrapper
@pro_print # 语法糖,在函数前使用用于装饰函数
def fun():
print('hello,python')
fun()
但装饰器会覆盖原有函数的函数名,提示文档等信息
def pro_print(fun): # 装饰器函数
def wrapper(*args,**kwargs): # 接收各种类型的不定长参数
'''执行函数前提示welcom to class'''
print("welcome to class")
fun()
return wrapper
@pro_print # 语法糖,在函数前使用用于装饰函数
def fun():
'''输出hello,python'''
print('hello,python')
fun()
print(fun.__name__)
print(fun.__doc__)
### 测试结果:
![](http://i2.51cto.com/images/blog/201812/14/c7afcd77bef6993d679f5062070febd5.jpg?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_30,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=)
>-----
### 导入functools中的wraps函数可以解决这个问题
from functools import wraps
def pro_print(fun): # 装饰器函数
@wraps(fun)
def wrapper(*args,**kwargs): # 接收各种类型的不定长参数
'''执行函数前提示welcom to class'''
print("welcome to class")
fun()
return wrapper
@pro_print # 语法糖,在函数前使用用于装饰函数
def fun():
'''输出hello,python'''
print('hello,python')
fun()
print(fun.__name__)
### 测试结果:
![](http://i2.51cto.com/images/blog/201812/14/45e9069889dfec16bbcc8141a90ae3cb.jpg?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_30,g_se,x_10,y_10,shadow_20,type_ZmFuZ3poZW5naGVpdGk=)