python闭包及装饰器

#装饰器:本质就是函数,功能是为其他函数添加附加功能

#原则:1.不修改被装饰函数的源代码  2.不修改被修饰函数的调用方式
#装饰器=高阶函数+函数嵌套+闭包


#函数嵌套:


# def bar():
#     print("form bar")
#
#
# def foo():
#     print("from foo")
#     def test():
#         pass


#函数嵌套
# def father(name):
#     print("from father %s"%name)
#     def son():
#         print("from son %s" %name)
#         def grandson():
#             print('from grandson')
#         grandson()
#     son()
#
# father("远军")




#函数嵌套
def father(name):
    print("from father %s"%name)
    def son():#函数名可以作为局部变量名
        print("from son")
        #{'son': <function father.<locals>.son at 0x0000028824B951E0>, 'name': 'alex'}
    #print(locals())
    son()

father("alex")
#装饰器的架子
import time
def  timer(func):#func=test
    def warrper():
        print(func)
        start=time.time()
        func()#就是在运行test
        stop=time.time()
        print("运行时间%s"%(start-stop))
    return warrper


@timer   #test=timer(test)
def test():
    time.sleep(3)
    print("test函数运行完毕")

#这样做的目的在于不改变函数的调用方式
# test=timer(test)#返回的是warrper的地址
# test()#执行warrper函数

#@timer  就相当于 test=timer(test)


test()

猜你喜欢

转载自www.cnblogs.com/tangcode/p/11087667.html