装饰器概念及运用
#!/user/bin/env python3
#-*-encoding="utf-8"-*-
1.装饰器概念
装饰器本身就是函数,为别的函数添加附加功能。把握两个遵循的条件。
1.不修改被修饰的源代码内容。
2.不修改被修饰函数的调用方式。
装饰器=高阶函数+函数嵌套+闭包
高阶函数定义:
1.函数接收的参数是一个函数名
2.函数的返回值是一个函数名
3.满足上述条件任意一个,都可称之为高阶函数
把函数当做参数传给高阶函数:
def foo():
print("我的函数名是做为一个高阶函数传给其它的函数的")
def fc1(fucn):
print("我是函数fc1,接受函数%s传过来的值" %fucn)
fucn()
def fc2(fucn):
print("我是函数fc2,函数返回值是%s" %fucn)
return fucn
fc1(foo)
fc2(foo)
import time
def foo():
time.sleep(0.2)
print("参数来自foo")
def fc1(fucn):
ks_time=time.time()
fucn()
js_time=time.time()
print("函数%s运行的时间是%s" %(fucn,js_time-ks_time))
fc1(foo)
import time
def foo():
print('from the foo')
def timmer(func):
start_time=time.time()
return func
stop_time=time.time()
print('函数%s 运行时间是%s' %(func,stop_time-start_time))
foo=timmer(foo)
foo()
#高阶函数总结
1.函数接收的参数是一个函数名
#作用:在不修改函数源代码的前提下,为函数添加新功能,
#不足:会改变函数的调用方式
2.函数的返回值是一个函数名
#作用:不修改函数的调用方式
#不足:不能添加新功能
#函数嵌套的例子:
def father(name):
print('from father %s' %name)
def son():
print('from son')
def grandson():
print('from grandson')
grandson()
son()
print(father('xfz'))
一层套一层的最里面的函数形成的就是一个闭包。
3.装饰器的框架
import time
def zsq(func):
def gongnenghanshu():
ks_time=time.time()
func()
js_time=time.time()
print("函数运行的时间是:%s" %(js_time-ks_time))
return gongnenghanshu
例子:
@zsq
def foo():
time.sleep(3)
print("运行了函数foo")
res=zsq(foo) #这是间接方式实现的装饰,但是更改了函数的调用方式.@语法甜糖,加到要调用装饰器的前面
res()
foo()
4.加返回值的方法 例2
import time
def zsq(func):
def gongnenghanshu():
ks_time=time.time()
res=func()
js_time=time.time()
print("函数运行的时间是:%s" %(js_time-ks_time))
return res
return gongnenghanshu
# 例子:
@zsq
def foo():
time.sleep(1)
print("运行了函数foo")
return "我是要添加的函数返回值"
z=foo()
print(z)