zoukankan      html  css  js  c++  java
  • python3 之装饰器学习

    import time
    
    
    def logger(func):
        def wrapper(*args,**kw):
            print('我准备开始计算;{} 函数了:'.format(func.__name__))
            func(*args,**kw)
    
            print('啊哈,我计算完啦。给自己加个鸡腿!!')
        return wrapper
    
    @logger
    def add(x,y):
        print('{} + {} = {}'.format(x, y, x+y))
    
    add(x= 200,y =50)
    
    
    
    def timer(func):
        def wrapper(*args,**kw):
            t1 = time.time()
            func(*args,**kw)
            t2 =time.time()
            cost_time =t2-t1
            print("花费时间:{}秒".format(cost_time))
        return wrapper
    
    @timer
    def want_sleep(sleep_time):
        time.sleep(sleep_time)
    
    
    
    want_sleep(10)
    
    
    
    
    def say_hello(contry):
        def wrapper(func):
            def deco(*args,**kw):
                if contry =='china':
                    print("你好")
                elif contry == "american":
                    print('hello .')
                else:
                    return
                func(*args,**kw)
            return deco
        return wrapper
    
    
    @say_hello('american')
    def american():
        print("I am from American")
    @say_hello('china')
    def chinese():
        print("我来自中国")
    
    
    american()
    print('-----------')
    chinese()
    

      

    最近因为在某公众号上看到装饰器用于测试异常处理,所以就学习了一下装饰器

  • 相关阅读:
    伟大的微软,太智能了
    ASP.NET MVC中的统一化自定义异常处理
    去除无用的文件查找路径
    关于easyUI的一些js方法
    easyUI小技巧-纯干货
    easyui tree tabs
    ueditor初始化
    多图联动
    饼图tooltip
    配色
  • 原文地址:https://www.cnblogs.com/Neotester/p/13330689.html
Copyright © 2011-2022 走看看