问题:函数名称的影响
案例1:打印函数名称
import time
def decorator(func):
def wrapper():
print(time.time())
func()
return wrapper
def fun1():
print(fun1.__name__)
fun1()
结果:fun1
案例2:
import time
def decorator(func):
def wrapper():
print(time.time())
func()
return wrapper
@decorator
def fun1():
print(fun1.__name__)
fun1()
结果:
1533381960.9017205
wrapper
案例3:添加函数注释
import time
def decorator(func):
def wrapper():
print(time.time())
func()
return wrapper
#@decorator
def fun1():
'''
这是fun1函数
:return:
'''
print(fun1.__name__)
#fun1()
print(help(fun1))
结果:
Help on function fun1 in module __main__:
fun1()
这是fun1函数
:return:
None
案例4:添加函数注释,添加装饰器
import time
def decorator(func):
def wrapper():
print(time.time())
func()
return wrapper
@decorator
def fun1():
'''
这是fun1函数
:return:
'''
print(fun1.__name__)
#fun1()
print(help(fun1))
结果:
Help on function wrapper in module __main__:
wrapper()
None
案例5:解决方案
import time
#导入functools库
from functools import wraps
def decorator(func):
@wraps(func)#使用wraps方法
def wrapper():
print(time.time())
func()
return wrapper
@decorator
def fun1():
'''
这是fun1函数
:return:
'''
print(fun1.__name__)
#fun1()
print(help(fun1))
结果:
Help on function fun1 in module __main__:
fun1()
这是fun1函数
:return:
None
总结:使用了functools库中的wraps方法