1. 程式人生 > >在函數被裝飾的情況下如何取消裝飾器,訪問原始函數

在函數被裝飾的情況下如何取消裝飾器,訪問原始函數

date 訪問 tool ror 幫助信息 函數 auth art run

在函數被裝飾器裝飾的情況下,需要保持原始函數的文檔,幫助信息等信息,或者直接調用原始函數,此時需要引入wraps模塊

#!/usr/bin/env python
#coding:utf-8
[email protected]: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("\nOrigin index function:\n")
	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("\nOrigin index function:\n")
	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!

在函數被裝飾的情況下如何取消裝飾器,訪問原始函數