装饰器--decorator2

装饰器加参数


 

import time

def timer(func):  # timer(test2) func = test2
	def deco():
		start_time = time.time()
		func()   # run test1()
		stop_time = time.time()
		print("the action time of the program is {}".format(stop_time-start_time))
	return deco   # 返回了deco的内存地址

@timer         # test2 = timer(test2)=deco
def test2(name):
	time.sleep(2)
	print("the name is {}".format(name))

test2("bigberg") # test2("bigberg") = deco("bigberg")

#输出
Traceback (most recent call last):
  File "G:/python/untitled/study3/decoration4.py", line 17, in <module>
    test2("bigberg")
TypeError: deco() takes 0 positional arguments but 1 was given
  1. 我们重新定义一个test2函数,并传入一个参数name,而函数运行报错 deco()没有传入参数。
  2. @timer 其实相当于 test2 = timer(test2) = deco
  3. test2("bigberg") = deco("bigberg") 

所以我们需要在嵌套函数 deco()中传入一个参数,才能确保程序正确

import time

def timer(func):  
	def deco(arg1):
		start_time = time.time()
		func(arg1)   
		stop_time = time.time()
		print("the action time of the program is {}".format(stop_time-start_time))
	return deco   # 返回了deco的内存地址

@timer
def test2(name):
	time.sleep(2)
	print("the name is {}".format(name))

test2("bigberg")

#输出
the name is bigberg
the action time of the program is 2.0001132488250732

  到这里传参已经实现了,但是如果参数个数不固定呢?我们还有非固定参数:

import time

def timer(func):  # timer(test1) func = test1
	def deco(*args,**kwargs):
		start_time = time.time()
		func(*args,**kwargs)   # run test1()
		stop_time = time.time()
		print("the action time of the program is {}".format(stop_time-start_time))
	return deco   # 返回了deco的内存地址

@timer
def test1():
	time.sleep(2)
	print("in the test1.")

@timer
def test2(name,age):
	time.sleep(2)
	print("the name is {} and age is {}".format(name,age))

test1()
test2("bigberg",18)

#输出
in the test1.
the action time of the program is 2.0002853870391846
the name is bigberg and age is 18
the action time of the program is 2.000582218170166

  由此可见使用非固定参数后,被修饰函数有没有参数都可以正常运行了。

 

posted @ 2017-03-28 19:15  Bigberg  阅读(410)  评论(0编辑  收藏  举报