装饰器

#_author:Xing
#date:2019/11/2
# 装饰器(函数)
# 1.作用域:L_E_G_B
# 2.高阶函数
# (1)函数名可以作为参数输入
# (2)函数名可以作为返回值
# 3.闭包
# 关于闭包:闭包=内部函数+定义函数时的环境
def outer():
x=10
def inner():#条件1:内部函数
print(x)#条件2:x为外部环境的一个变量
return inner#结论:内部函数inner就是一个闭包
outer()()#10
#inner局部变量,全局不能调用
#关于闭包:
#闭包=内部函数+定义函数时的环境
print('-------------')
def outer(x):
def inner():#条件1:内部函数
print(x)#条件2:x为外部环境的一个变量
return inner#结论:内部函数inner就是一个闭包
f=outer(8)
f()#8
print('-------------')
# import time
# start=time.time()
# time.sleep(1)
# end=time.time()
# print(end - start)#1.016906499862671
print('-------------')
#遵守开放封闭原则

# def showtime(f):
# start = time.time()
# f()
# end = time.time()
# print('spend %s' % (end - start)) # spend 3.0004241466522217
# showtime(fun)
#改进
def fun():
print('function...')
time.sleep(3)
import time
def showtime(f):
def inner():
start = time.time()
f()
end = time.time()
print('spend %s' % (end - start)) # spend 3.0004241466522217
return inner
fun=showtime(fun)
fun()
#执行结果:
# function...
# spend 3.0003504753112793





posted @ 2019-11-02 12:01  Stary_tx  阅读(140)  评论(0编辑  收藏  举报