返回顶部

【今日代码段】--装饰器

#装饰器
import time
def logger(flag = ""):
    def show_time(f):
        def inner(*x,**y):
            start = time.time()
            f(*x,**y)      #这里的f代表实际调用的函数
            end = time.time()
            print("spend %s" %(end-start))
            if flag == "true":
                print("打开日志记录")    #这里可以使用with open  打开文件操作
        return inner
    return show_time
@logger("true")    # @show_time    ==    add=show_time(add)
def add(*a,**b): #  *a:不定长函数(元组),**b:不定长函数(列表等),这里没有用到**b
    sums = 0
    for i in a:
        sums+=i
    print(sums)
    time.sleep(1)

add(1,2,3,5,6,7)  #实参,实际调用

@logger("true")
def too():
    print("qqqqqqq")
    time.sleep(2)

too()   #调用 show_time函数后,执行too

 

posted @ 2016-09-07 17:12  Will_D_Zhang  阅读(121)  评论(0编辑  收藏  举报