Python 装饰器(闭包)
1.闭包 closure
如果在一个内部函数里面,对在外部作用域(非全局作用域)的变量进行引用,那么内部函数就被认为是闭包
例子
def f(): x=10 #外部作用域 def func():#内部函数 x=7 #外部作用域的变量 return return func #内部函数func为闭包 a=f() a()
闭包就是函数块+定义函数时的环境
2.闭包的应用--装饰器
作用:为原来的函数新增新的功能
2.1 普通写法
def foo(): return none def show_time(func): #show_time 为装饰器函数 def inner(): start=time.time() func() end=time.time() print (end-start) return inner foo=show_time(foo) foo()
改造函数foo,且不影响现有的foo函数内容
2.2 python写法
def show_time(func): #show_time 为装饰器函数 def inner(): start=time.time() func() end=time.time() print (end-start) return inner @show_time #foo=show_time(foo) def foo(): return none foo()
2.3 python加参数写法 功能函数加参数
def show_time(func): #show_time 为装饰器函数 def inner(x,y): start=time.time() func(x,y) end=time.time() print (end-start) return inner @show_time #foo=show_time(foo) def foo(a,b): return none foo()
2.4 show_time加参数 装饰器函数加参数
def logger(flag): def show_time(func): #show_time 为装饰器函数 def inner(x,y): start=time.time() func(x,y) end=time.time() if flag=='true': print (end-start) return inner return show_time @logger(flag='true') def foo(a,b): return none foo(a,b)
可以通过传参数控制是否执行某部分代码
浙公网安备 33010602011771号