首页 > 编程语言 >python 装饰器

python 装饰器

时间:2022-10-07 14:23:00浏览次数:86  
标签:__ name python doc wrapper print test 装饰

python 装饰器

原文:https://blog.csdn.net/weixin_40576010/article/details/88639686
装饰器的作用: 在不改变原有功能代码的基础上,添加额外的功能,如用户验证等。
@wraps(view_func)的作用: 不改变使用装饰器原有函数的结构(如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,这样子可能会造成后面查找该方法的名字已经注释时候会得到装饰器的内嵌函数的名字和注释。

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__

"""

标签:__,name,python,doc,wrapper,print,test,装饰
From: https://www.cnblogs.com/bitterteaer/p/16759656.html

相关文章