美文网首页
Python装饰器

Python装饰器

作者: 将军红 | 来源:发表于2019-12-19 17:02 被阅读0次
    # encoding=utf-8
    
    import time
    
    
    # def comsume(f):
    #     def wrapper(*args, **kwargs):
    #         t1 = time.time()
    #         result = f(*args, **kwargs)
    #         t2 = time.time()
    #         print t2-t1
    #         return result
    #     return wrapper
    #
    #
    # @comsume
    # def sum(start, end):
    #     result = start
    #     for i in range(start, end):
    #         result += i
    #     return result
    
    # 带参数的装饰器
    def consume(times):
        def func(f):
            print 'run with para times=%s'%times
    
            def wrapper(*args, **kwargs):
                t1 = time.time()
                result = f(*args, **kwargs)
                t2 = time.time()
                print t2-t1
                return result
            return wrapper
        return func
    
    
    @consume(times=3)
    def sum(start, end):
        result = start
        for i in range(start, end):
            result += i
        return result
    
    
    if __name__ == '__main__':
        print sum(1, 10000)
        # consume(times)(ff)(1, 1000)
    

    import time
    
    
    def consume(f):
        def wrapper(*args, **kwargs):
            t1 = time.time()
            s = f(*args, **kwargs)
            t2 = time.time()
            print 'time', t2 - t1
            return s
    
        return wrapper
        # consume(fff)=wrapper
    
    
    def fff(x, y):
        return x + y
    
    print consume(fff)(1, 2)
    

    相关文章

      网友评论

          本文标题:Python装饰器

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