美文网首页
函数的修饰器

函数的修饰器

作者: tenro | 来源:发表于2021-02-02 21:50 被阅读0次
    import time
    
    # 定义一个修饰器,用来计算函数的执行时间
    
    
    def show_time(func):
    def inner():
        start_time = time.time()
        func()
        end_time = time.time()
        print('spend %s' % (end_time - start_time))
    return inner
    
    # @show_time将修饰器注入到函数当中,类似foo = show_time(foo)
    
    
    @show_time
    def foo():
        print('我需要一个修饰器')
        time.sleep(2)
    
    
    # foo = show_time(foo)
    foo()

    相关文章

      网友评论

          本文标题:函数的修饰器

          本文链接:https://www.haomeiwen.com/subject/edjutltx.html