装饰器:
定义:本质是函数,主要目的是为了给其他的函数增加附加功能
原则:
1.不能修改被装饰函数的源代码
2.不能修改被装饰的函数调用方式
实现装饰器知识:
1.函数就是“变量”
2.高阶函数
a:把一个函数名当做实参传递给另外一个函数
b:返回值中包含函数名
eg:
def bar():
print 'in the bar'
def foo(func):
res=func()
return res
foo(bar)
优秀之处:
def foo(func):
return func
print 'Function body is %s' %(foo(bar))
print 'Function name is %s' %(foo(bar).func_name)
foo(bar)()
#foo(bar)() 等同于bar=foo(bar)然后bar()
bar=foo(bar)
bar()
3.嵌套函数
eg:
def foo():
print 'in the foo'
def bar():
print 'in the bar'
bar()
foo()
# bar()
局部与全局作用域的访问顺序:由内层向外层逐层查找
x=0
def grandpa():
# x=1
def dad():
x=2
def son():
x=3
print x
son()
dad()
grandpa()
高阶函数+嵌套函数==>>装饰器
eg:
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 func run time is %s" %(stop_time-start_time))
return deco
@timer #test1=timer(test1)
def test1():
time.sleep(3)
print("in the test1")
test1()