第十五天,装饰器
1 .作用域:L_E_G _B
L局部变量 E嵌套变量 G全局变量 B内置变量
x=10 def f(): t=5 def inner(): count=7 return=1
2.高阶函数
1.函数名可以作为参数输入
2.函数名可以作为返回值
3.闭包函数
def outer(): x=10 def inner(): #条件1 inner就是内部函数 c=10 print(x) #条件2 外部环境的一个变量 return inner #结论:内部函数inner 就是一个闭包 #outer()() #inner() 局部变量,全局无法调用
装饰器
1.计时器函数
import time def foo(): print("wwrw sfe") time.sleep(3) def count_time(f): start = time.time() f() end = time.time() print("spend%s" % (end - start)) count_time(foo) # wwrw sfe # spend3.000171661376953
2.装饰器 +@count_time 调用方法
#实现函数的调用和计算时间 装饰器 import time def foo(): print("wwrw sfe") time.sleep(3) end=time.time() def count_time(f): def inner(): start = time.time() f() end = time.time() print("spend%s" % (end - start)) return inner foo=count_time(foo) #指向inner 的内存地址 foo() # wwrw sfe # spend3.000171661376953 @count_time #等价于把bar=count_time(bar) count_time 后面跟的函数就是被计算函数 def bar(): time.sleep(4) print("21141") bar() # wwrw sfe # spend3.001171588897705
3.三层装饰器+@logger(参数)
#实现函数的调用和计算器 装饰器 import time def logger(flag=""): #新加了一个参数用于控制函数操作 def count_time(f): def inner(*args): start = time.time() f(*args) end = time.time() print("spend%s" % (end - start)) if flag=="true": print("ewfw") return inner return count_time @logger("true") #新加了一个参数用于控制函数操作 def add(*args): #功能函数 sum=0 for i in args: sum+=i time.sleep(1) print(sum) add(2,41,3,23,253,35,3,234,52) # 646 # spend1.0000572204589844 # ewfw