python——装饰器(不定长参数,闭包,装饰器)示例
1 def func(functionName): 2 print("正在装饰") 3 def func_in(*args, **kargs): 4 print("------func_in---1--") 5 res = functionName(*args, **kargs) 6 print("------func_in---2---") 7 return res 8 print("装饰结束") 9 return func_in 10 11 # 再还没有执行test函数的时候就开始装饰 12 @func 13 def test(a, b): 14 print("--------test a=%d b=%d -----" % (a, b)) 15 16 @func 17 def test2(a, b, c, d): 18 print("--------test2 %d %d %d %d -------" % (a, b, c, d)) 19 20 @func 21 def test3(): 22 return "hahaha" 23 24 print("%%%%%%%%%%%%%%%%%%% 不定长参数 %%%%%%%%%%%%%%%%") 25 test(1, 2) 26 test2(1, 2, 3, 4) 27 print("%%%%%%%%%%%%%%%%%%% 返回值 %%%%%%%%%%%%%%%%") 28 res = test3() 29 print("test3 return value is %s" % res)
运行结果:
正在装饰 装饰结束 正在装饰 装饰结束 正在装饰 装饰结束 %%%%%%%%%%%%%%%%%%% 不定长参数 %%%%%%%%%%%%%%%% ------func_in---1-- --------test a=1 b=2 ----- ------func_in---2--- ------func_in---1-- --------test2 1 2 3 4 ------- ------func_in---2--- %%%%%%%%%%%%%%%%%%% 返回值 %%%%%%%%%%%%%%%% ------func_in---1-- ------func_in---2--- test3 return value is hahaha
装饰器中return
1 from time import ctime, sleep 2 def func_args(args = "hello"): 3 def func(functionName): 4 print("正在装饰") 5 def func_in(): 6 print("###### %s called in %s used %s ######" % (functionName.__name__, ctime(), args)) 7 functionName() 8 return func_in 9 return func 10 11 # 先执行func_args("hahah"),给args赋值,返回func的引用 12 # @func 13 # 使用@func对函数进行装饰 14 @func_args("hahah") 15 def test1(): 16 print("--------test1--------") 17 18 @func_args("heihei") 19 def test2(): 20 print("---------test2----------") 21 22 # 带有参数的装饰器,能够起到,在运行时,根据参数值得不同,实现不同的功能 23 test1() 24 test2()
运行结果:
正在装饰 正在装饰 ###### test1 called in Sun Aug 26 14:53:34 2018 used hahah ###### --------test1-------- ###### test2 called in Sun Aug 26 14:53:34 2018 used heihei ###### ---------test2----------