zoukankan      html  css  js  c++  java
  • python day100-[day16-20]-3 函数的使用方法

    装饰器函数

    20200309


    • 例子1
    import time
    
    
    def record_time(func):
        """自定义装饰函数的装饰器"""
    
        # @wraps(func)
        def inner(*args, **kwargs):
            start = time.time()
            result = func(*args, **kwargs)
            print(f'{func.__name__}: {time.time() - start}秒')
            return result
    
        return inner
    
    
    @record_time
    def testfun(t):
        time.sleep(t)
        print("休息了%d秒!" % t)
    
    testfun(2)
    print(testfun.__name__)#注意
    
    #输出
    休息了2秒!
    testfun: 2.0001144409179688秒
    inner #注意
    
    • 例子 2 调用wraps
    from functools import wraps
    import time
    
    
    def record_time(func):
        """自定义装饰函数的装饰器"""
    
        @wraps(func)
        def wrapper(*args, **kwargs):
            start = time.time()
            result = func(*args, **kwargs)
            print(f'{func.__name__}: {time.time() - start}秒')
            return result
    
        return wrapper
    
    
    @record_time
    def testfun(t):
        time.sleep(t)
        print("休息了%d秒!" % t)
    
    testfun(2)
    print(testfun.__name__) #注意
    
    # 输出
    休息了2秒!
    testfun: 2.000285863876343秒
    testfun #注意
    
    • 参考
    https://blog.csdn.net/legend818/article/details/95165703
    
  • 相关阅读:
    jquery autocomplete
    hibernate 数据缓存
    Python变量类型
    Python基础语法
    Python环境搭建
    Python简介
    python下载地址
    第十、十一章,软件测试和软件演化
    第九章,软件实现
    第八章,面向对象设计
  • 原文地址:https://www.cnblogs.com/damahuhu/p/12427280.html
Copyright © 2011-2022 走看看