python 装饰器

装饰器1.函数作用域2.高阶函数3.闭包
def outer():
    x=10
    def inner(): #闭包条件一 inner是内部函数
        print(x) #条件二  外部环境的一个变量

    return inner  #内部函数inner就是闭包
inner()局部变量,全局无法调用
闭包=函数块+定义函数是的环境(给原函数增加新的功能)
import time


def show_time(f):
    def inner(*x,**y):
        start=time.time()
        f(*x,**y)
        end=time.time()
        print('spend %s second'%(end-start))
    return inner


@show_time# 等价于foo=show_time(foo)
def foo():
    print('foo...')
    time.sleep(2)

@show_time
def add(*a,**b):
    sum=0
    for i in a:
        sum+=i
    print(sum)
    time.sleep(2)
# foo=show_time(foo)
foo()
add(1,2,3,4,5)

#  *: 该位置接受任意多个非关键字(non-keyword)参数,在函数中将其转化为元组(1,2,3,4)
#  **:该位置接受任意多个关键字(keyword)参数,在函数**位置上转化为词典 [key:value, key:value ]
import time

def logger(flag):
    def show_time(f):
        def inner(*x,**y):
            start=time.time()
            f(*x,**y)
            end=time.time()
            print('spend %s second'%(end-start))
        return inner
    return show_time


@logger('true')# 等价于@show_time
def add(*a,**b):
    sum=0
    for i in a:
        sum+=i
    print(sum)
    time.sleep(2)

add(1,2,3,4,5)

 

posted @ 2018-10-27 17:17  ErnestLi  阅读(73)  评论(0)    收藏  举报