python带参数的装饰器,小程序

下面的python小程序,给出了一个带参数的装饰器的应用

import time    
def logger(flag):    
    def show_time(f):
        def inner(x,y):
            start = time.time()
            f(x,y)
            end = time.time()
            print(end - start)
            if flag:
                with open('log.txt','a') as file1:
                    file1.write("The run time of the last programme is %s\n" %end)
                    print("logger is running....")
                    
        return inner
    return show_time

@logger(True)
def Add(x,y):
    print(x + y)

Add(1,2)
Add(8,9)

运行结果如下:
3
8.70227813721e-05
logger is running....
17
3.60012054443e-05
logger is running....

 

posted @ 2019-11-26 09:06  Iceberg_710815  阅读(164)  评论(0编辑  收藏  举报