Python装饰器中@wraps作用

装饰器的作用: 在不改变原有功能代码的基础上,添加额外的功能,如用户验证等。
@wraps(view_func)的作用: 不改变使用装饰器原有函数的结构(如name, doc)

1.不使用@wraps装饰器时候,看看__name__、__doc__输出的内容是什么
def decorator(func):
	"""this is decorator __doc__"""
	def wrapper(*args, **kwargs):
		"""this is wrapper __doc__"""
		print("this is wrapper method")
		return func(*args, **kwargs)
	return wrapper

@decorator
def test():
	"""this is test __doc__"""
	print("this is test method")

print("__name__: ", test.__name__)
print("__doc__:  ", test.__doc__)
"""
结果:
__name__:  wrapper

__doc__:   this is wrapper __doc__
"""

分析: 对test()方法进行装饰时候,实际上是
test = decorator(test)
返回的是wrapper方法的引用,也就是让test指向了wrapper方法,所以调用test.__name__, 实际上是wrapper.__name__,这样子可能会造成后面查找该方法的名字已经注释时候会得到装饰器的内嵌函数的名字和注释。

2. 使用@wraps装饰器解决这个问题
from functools import wraps
def decorator(func):
	"""this is decorator __doc__"""
	@wraps(func)
	def wrapper(*args, **kwargs):
		"""this is wrapper __doc__"""
		print("this is wrapper method")
		return func(*args, **kwargs)
	return wrapper

@decorator
def test():
	"""this is test __doc__"""
	print("this is test method")

print("__name__: ", test.__name__)
print("__doc__:  ", test.__doc__)
"""
结果:
__name__:  test

__doc__:   this is test __doc__

"""

你可能感兴趣的:(装饰器,python,装饰器,@wraps)