装饰器--decorator3

装饰器添加返回值

import time
def timer(func):
	def wrapper(*args,**kwargs): #wrapper包装的意思
		start_time = time.time()
		func(*args,**kwargs)
		stop_time = time.time()
		print("The run time of the function is {}".format(stop_time-start_time))
	return wrapper

@timer
def cacl(number):
	start_num = 1
	total = 0
	while start_num < number:
		if start_num % 2 == 1:
			total += start_num
		else:
			start_num += 1
			continue
		start_num += 1
	return total

print(cacl(1000000))

#输出
The run time of the function is 0.172149658203125
None

  我们定义一个函数用来计算1000000内奇数之和,并返回其计算结果。同样我们使用一个装饰器来计算该程序的运行时间。可以看到我们最后的运行结果中,返回值是 None

  我们已经知道如下:

  1. @timer ---> cacl = wrapper(cacl)
  2. cacl()函数当中有返回值,但是 wrapper()函数中没有返回值,所以最后输出的结果为 None

增加返回结果

import time
def timer(func):
	def wrapper(*args,**kwargs): #wrapper包装的意思
		start_time = time.time()
		res = func(*args,**kwargs)
		stop_time = time.time()
		print("The run time of the function is {}".format(stop_time-start_time))
		return res  #添加一个返回值
	return wrapper

@timer
def cacl(number):
	start_num = 1
	total = 0
	while start_num < number:
		if start_num % 2 == 1:
			total += start_num
		else:
			start_num += 1
			continue
		start_num += 1
	return total

#输出
The run time of the function is 0.169450044631958
250000000000

  

原文地址:https://www.cnblogs.com/bigberg/p/6638453.html