wklken的笔记 2020-03-27
未加@wraps
# def tag(name):# def decorator(func):# def wrapper(text):# value=func(text)# return "<{name}>{value}</{name}>".format(name=name,value=value)# return wrapper# return decorator## @tag("p")# def my_upper(text):# value=text.upper()# return value# print (my_upper("hello"))# print (my_upper.__name__)输出:wrapper
加上@wraps
def tag(name): def decorator(func): @wraps(func) def wrapper(text): value=func(text) return "<{name}>{value}</{name}>".format(name=name,value=value) return wrapper return decorator@tag("p")def my_upper(text): value=text.upper() return valueprint (my_upper("hello"))print (my_upper.__name__)输入:my_upper二者之间的区别在于加上@wraps 原函数func被decorator(装饰器)作用后,函数性质不变