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

    1、开放封闭原则:对扩展开放、对修改是封闭
    2、装饰器:装饰它人的,器指的是任意可调用对象,现在的场景装饰器(函数)
    被装饰的对象也是函数
    原则:1、不修改装饰对象的源代码;2、不修改被装饰对象的调用方式
    装饰器的目的:在遵循1,2的前提下为被装饰对象添加上新功能

    一、无参装饰器
    import time
    def timmer(func):
    def inner():
    start = time.time()
    func()
    end = time.time()
    print("run time is %s" %(end - start))
    return inner

    @timmer #相当于index = timmer(index)
    def index():
    time.sleep(3)
    print("welcome to index")

    index() #相当于inner()
    输出结果:welcome to index
    run time is 3.0010766983032227


    改进一:
    import time
    def timmer(func):
    def inner():
    start = time.time()
    res = func()
    end = time.time()
    print("run time is %s" %(end - start))
    return res
    return inner

    @timmer 相当于index = timmer(index)
    def index():
    time.sleep(3)
    print("welcome to index")
    return 1111

    res = index() #相当于res = inner()
    print(res)
    输出结果:welcome to index
    run time is 3.0010766983032227
    1111

    改进二:
    import time
    def timmer(func):
    def inner(*args,**kwargs):
    start = time.time()
    res = func(*args,**kwargs)
    end = time.time()
    print("run time is %s" %(end - start))
    return res
    return inner

    @timmer #相当于index = timmer(index)
    def index(name):
    time.sleep(3)
    print("welcome %s to index" %name)
    return 1111

    res = index('keke') #相当于res = inner('keke')
    print(res)
    输出结果:welcome keke to index
    run time is 3.000697135925293
    1111

    二、有参装饰器
    import time
    def outter(file):
    def welcome(func):
    def inner():
    name = input("name>>:").strip()
    res = func(name)
    if file == 'mysql':
    print("mysql")
    elif file == 'mangodb':
    print('mangodb')
    else:
    print('others!!!')
    return res
    return inner
    return welcome

    @outter(file='mangodb') 相当于@welcome index=welcome(index)
    def index(name):
    time.sleep(3)
    print('welcome %s to index' %name)
    return 1111

    res = index()
    print(res)

    输出结果:name>>:keke
    welcome keke to index
    mangodb
    1111





  • 相关阅读:
    linux mysql添加用户名并实现远程访问
    bootstrap-datetimepicker时间控件的使用
    jquery图片左右来回循环飘动
    jquery 全选获取值
    设置linux编码utf-8
    nginx 自签名https
    Laravel 邮件配置
    memcachq队列安装
    开发与运维使用常用工具
    composer配置和安装php框架
  • 原文地址:https://www.cnblogs.com/keqing1108/p/13509406.html
Copyright © 2011-2022 走看看