为了能到远方,脚下的每一步都不能少.|

bitterteaer

园龄:3年8个月粉丝:1关注:0

python 装饰器

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__

"""

本文作者:bitterteaer

本文链接:https://www.cnblogs.com/bitterteaer/p/16759656.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   bitterteaer  阅读(12)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起