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

    装饰器:本质是函数,(装饰其他函数),就是为其他函数添加附加功能。

    原则:1,不能修改被装饰函数的原代码。

    2、不能修改被装饰函数的调用方式。

    import time
    
    def timer(func):
        def warpper(*args,**kwargs):
            start_time=time.time()
            func()
            stop_time=time.time()
            print("The func run time is %s " %(stop_time-start_time))
        return warpper
    
    @timer
    def test1():
        time.sleep(3)
        print("in the test1")
    
    @timer
    def test2():
        time.sleep(5)
        print("in the test2")
    
    test1()
    test2()

    实现装饰器的功能:1。函数就是变量。

    2、高阶函数。

    a。把一个函数当和一个形参传递给另一个函数当实能。b、当返回值中包含函数名。

    def bar():
        print("in the bar")
    
    def test1(func):
        print(func)
    
    test1(bar)
    test1(bar())
    '''def bar():
        print("in the bar")
    
    def test1(func):
        print(func)
    
    test1(bar)
    test1(bar())'''
    
    import time
    def bar():
        time.sleep(3)
        print("in the bar")
    
    def test2(func):
        print(func)
        return func
    
    #print(test2(bar))
    t=test2(bar)
    #print(t)
    t() #run bar

    3、嵌套函数。

    高阶函数+嵌套函数=装饰器

  • 相关阅读:
    关于代码手写UI,xib和StoryBoard
    封装自己的framework静态库
    AsyncDisplayKit
    RunLoop
    AFNetworking2.0源码解析<三>
    AFNetworking2.0源码解析<四>
    AFNetworking2.0源码解析<二>
    AFNetworking2.0源码解析<一>
    多线程
    Mac svn 命令
  • 原文地址:https://www.cnblogs.com/lyzfp/p/12297658.html
Copyright © 2011-2022 走看看