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

天大地大妈咪最大 提交于 2019-11-26 09:48:11

下面的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)运行结果如下:38.70227813721e-05logger is running....173.60012054443e-05logger is running....

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!