• 装饰器


    1.器指的是工具,而程序中的函数就是具备某一功能的工具。

    装饰指的是为被装饰对象添加额外功能。

    2.就目前的知识来看,定义装饰器就是定义一个函数,只不过该函数的功能就是用来为其他函数添加额外的功能。

    3.装饰器本身其实可以是任意可调用的对象。

     被装饰的对象也可以是任意可调用的对象。

    4.为什么要用装饰器:

    软件的开发要符合开放-封闭原则

    开放-封闭原则指的是:软件一旦上线运行后对修改源代码是封闭的,对扩展功能是开放的。

    这就用到了装饰器。

    装饰器的实现必须遵循两大原则:

    1.不修改被装饰对象的源代码

    2.不修改被装饰对象的调用方式

    装饰器其实就是在遵循1和2原则的前提下为被装饰对象添加新功能。

    5.如和用装饰器:

    import time
    违反了不能改变装饰对象的源代码
    def index():
    start=time.time()
    print('welcom to index')
    time.sleep(3)
    stop=time.time()
    print('run time is %s' %(stop-start))
    index()

    import time
    没有违反两大原则,但是每次计算都要写一遍很麻烦,index,f2 都要写一次。
    def index():
    print('welcom to index')
    time.sleep(3)

    def f2():
    print('from f2')
    time.sleep(2)

    start=time.time()
    index()
    stop=time.time()
    print('run time is %s' %(stop-start))

    start=time.time()
    f2()
    stop=time.time()
    print('run time is %s' %(stop-start))


    import time
    违反了不能改变调用方式的原则
    def index():
    print('welcom to index')
    time.sleep(3)

    def timmer(func):
    start=time.time()
    func()
    stop=time.time()
    print('run time is %s' %(stop-start))

    timmer(index)




    '''
    import time

    def index():
    print('welcome to index')
    time.sleep(3)

    def timmer(func): #func=最原始的index
    # func=index
    def inner():
    start=time.time()
    func()
    stop=time.time()
    print('run time is %s' %(stop-start))
    return inner

    # f=timmer(index)
    # f()

    # index=timmer(里面是被装饰函数的内存地址)
    index=timmer(index) #index=inner

    index() #inner()


    '''
    import time

    def index():
    print('welcom to index')
    time.sleep(3)

    def timmer(func):
    #func=最原始的index
    def wrapper():
    start=time.time()
    func()
    stop=time.time()
    print('run time is %s' %(stop - start))
    return wrapper

    index=timmer(index) #index=wrapper函数的内存地址
    index()
  • 相关阅读:
    HTML5学习总结-番外05 http 状态码
    Python开发技巧
    QPushButton class
    Qt class
    QTableWidgetItem class
    毕业设计进度10
    毕业设计进度9
    毕业设计进度8
    毕业设计进度7
    毕业设计进度6
  • 原文地址:https://www.cnblogs.com/Roc-Atlantis/p/9168938.html
Copyright © 2020-2023  润新知