zoukankan      html  css  js  c++  java
  • 在函数被装饰的情况下如何取消装饰器,访问原始函数

    在函数被装饰器装饰的情况下,需要保持原始函数的文档,帮助信息等信息,或者直接调用原始函数,此时需要引入wraps模块

    #!/usr/bin/env python
    #coding:utf-8
    #@Author:Andy
    # Date: 2017/6/14
    
    
    import time
    from random import randrange
    
    # 装饰器
    def timer(func):
    	"""
    	Measure function's running time
    	"""
    	def wrapper(*args, **kwargs):
    		start_time = time.time()
    		func(*args, **kwargs)
    		stop_time = time.time()
    		print("Run time is %s" % (stop_time - start_time))
    	return wrapper
    
    @timer
    # 被装饰函数
    def index(n:int):
    	time.sleep(randrange(1, 5))
    	print("I was decorated!")
    
    
    if __name__ == '__main__':
    	index(5)
    	print("function name:",index.__name__)
    	print("doc:",index.__doc__)
    	print("annotations:", index.__annotations__)
    	print("
    Origin index function:
    ")
    	origin_index = index.__wrapped__
    #AttributeError: 'function' object has no attribute '__wrapped__'
    	#origin_index(10)
    

     上面因为没有引入wraps ,会出现attribueError错误,引入wraps后:

    import time
    from random import randrange
    from functools import wraps
    
    # 装饰器
    def timer(func):
    	"""
    	Measure function's running time
    	"""
    	@wraps(func)
    	def wrapper(*args, **kwargs):
    		start_time = time.time()
    		func(*args, **kwargs)
    		stop_time = time.time()
    		print("Run time is %s" % (stop_time - start_time))
    	return wrapper
    
    @timer
    # 被装饰函数
    def index(n:int):
    	"""
    	Decorated function
    	"""
    	time.sleep(randrange(1, 3))
    	print("I was decorated!")
    
    
    if __name__ == '__main__':
    	index(5)
    	print("function name:",index.__name__)
    	print("doc:",index.__doc__)
    	print("annotations:", index.__annotations__)
    	print("
    Origin index function:
    ")
    	origin_index = index.__wrapped__
    	origin_index(10)
    

     结果:

    I was decorated!
    Run time is 2.0009963512420654
    function name: index
    doc: 
    	Decorated function
    	
    annotations: {'n': <class 'int'>}
    
    Origin index function:
    
    I was decorated!
    
  • 相关阅读:
    Java面向对象之继承
    ios Block解决循环引用和回传值
    iOS 计算label的高度
    十六进制的颜色
    App调SDK时加判断
    vmware中clone后的工作
    关于python保留几位小数,不进行四舍五入的方法
    git 绑定github
    opensuse ./filezilla: error while loading shared libraries: libpng12.so.0: cannot open shared object file: No such file or directory
    关于opensuse开机登录背景修改后,不生效的问题
  • 原文地址:https://www.cnblogs.com/Andy963/p/7015824.html
Copyright © 2011-2022 走看看