Python 函数装饰器学习
函数装饰器作用:
函数装饰器的应用及特点
#原则:
#1.不能修改被装饰函数的源代码,
#2、不能修改函数的调用方式。
#实现装饰器知识储备
# 1、函数即“变量”
# 2、高阶函数:
# 1)把一个函数名当做实参传递给另外一个函数
# 函数(在不修改被装饰函数源代码的情况下为其添加功能)
# 2)返回值中包含函数名的函数
# 不修改函数的调用方式
# 3、嵌套函数
# 高阶函数+嵌套函数==》 装饰器效果
#举例:简易装饰器例子 import time def timmer(func): def warpper(*args,**kwargs): start_time=time.time() func() stop_time=time.time() print("the func run time is %s" %(stop_time-start_time)) return warpper @timmer def test1(): time.sleep(3) print("in the test1") test1() #类2 : 证明装饰函数不分先后定义,与定义变量相同,关系即为平等;定义完即可引用。 def bar(): '''函数即“变量”''' print('in the bar1') def foo(): print('in the bar') bar() foo() def foo1(): print('in the foo1') bar1() def bar1(): print('in the bar2') foo1() # 匿名函数 bcname=lambda x:x*3 #这个函数没有名字 , 他把这个函数赋值给一个变量。 print(bcname(4)) #函数就是变量, 定义一个函数就类似于变量 #高阶函数实例: _______第一种高阶函数实例__________ def barg(): print("in the barg,",'高阶函数实例1测试'.center(50,'#')) def test1(fucn): print(fucn) fucn() test1(barg) #输出的是内存地址 #高阶函数的作用: #实例如下: def barg2(): time.sleep(4) print('in the barg2',"高阶函数应用".center(60,'-')) def test2(func2): strat2_time=time.time() func2() stop2_time=time.time() print("the func run time is %s" % (stop2_time - strat2_time)) test2(barg2) #返回值包含函数名的函数 def bar_test(): print("in the bar_test","返回值包含函数名的函数".center(60,'-')) def test_no(funcc): print(funcc) return funcc bar_test=test_no(bar_test) bar_test()
#####装饰器应用####
import time def timer(func): def deco(): start_time=time.time() func() stop_time=time.time() print('zhe run time is:%s'%(stop_time-start_time)) return deco @timer ##应用装饰器 def test1(): time.sleep(4) print("in the test1") @timer #应用装饰器 def test2(): time.sleep(3) print("in the test2") # test1=timer(test1) # test2=timer(test2) test1() test2()

浙公网安备 33010602011771号