zoukankan      html  css  js  c++  java
  • 装饰器

    import  time
    def test():
        time.sleep(3)
        print('我是test')
    #test();
    #用高阶函数实现一个装饰器 来统计函数执行时间
    
    def timmer(func):
        def wapper():
            start_time=time.time()
            func()
            stop_time=time.time()
            print('函数%s的执行时间是%s' %(func.__name__, (stop_time-start_time)))
        return  wapper
    #res=timmer(test) #res() #用函数堂的方法 @+修饰函数名 就相当于 res=timmer(test) 这步操作 @timmer def test2(): time.sleep(3) print('我是test2') test2()

     带返回值的

    import  time
    def test():
        time.sleep(3)
        print('我是test')
    #test();
    #用高阶函数实现一个装饰器 来统计函数执行时间
    
    def timmer(func):
        def wapper():
            start_time=time.time()
            res=func()
            stop_time=time.time()
            print('函数%s的执行时间是%s' %(func.__name__, (stop_time-start_time)))
            return  res
        return wapper
    
    #res=timmer(test)
    #res()
    #用函数堂的方法   @+修饰函数名 就相当于 res=timmer(test) 这步操作
    @timmer
    def test2():
        time.sleep(3)
        return '我是test2的返回值'
    
    res=test2()
    print(res)

     带参数

    import  time
    def timmer(func):
        def wapper(*args,**kwargs):
            start_time=time.time()
            res=func(*args,**kwargs)
            stop_time=time.time()
            print('函数%s的执行时间是%s' %(func.__name__, (stop_time-start_time)))
            return  res
        return wapper
    #带参数
    @timmer
    def test2(name,age):
        time.sleep(1)
        print('我是%s今年%s岁' %(name,age))
        return '我是test2的返回值'
    
    res=test2('alex',18)
    print(res)
  • 相关阅读:
    Codeforces Round #276 (Div. 1) D. Kindergarten dp
    Codeforces Round #221 (Div. 1) B. Maximum Submatrix 2 dp排序
    hihoCoder Challenge 27 #1469 : 福字 dp
    Codeforces Beta Round #5 C. Longest Regular Bracket Sequence 括号序列 dp+栈
    Python id() 函数
    Python divmod() 函数
    Python any() 函数
    Python next() 函数
    Python slice() 函数
    Python3 hex() 函数
  • 原文地址:https://www.cnblogs.com/jiawen010/p/9723029.html
Copyright © 2011-2022 走看看