zoukankan      html  css  js  c++  java
  • Python学习之路:装饰器前奏

    装饰器:

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

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

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

    实现装饰器知识储备:

    1、函数即“变量”

    2、高阶函数

    a:把一个函数名当作实参传给另外一个函数

    b:返回值中包含函数名(不修改函数的调用方式)

    3、嵌套函数

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

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

    匿名函数:不需要起名字(内存回收)

    calc = lambda x:x*3
    print(calc(3))
    
    #函数即“变量”
    
    # def foo():
    #     print('in the foo')
    #     bar()
    # foo()
    
    #----------------------
    def bar():
        print('in the bar')
    
    def foo():
        print('in the foo')
        bar()
    foo()
    
    
    
    #-----------------------------------------------
    def foo():
        print('in the foo')
        bar()
    def bar():
        print('in the bar')
    foo()
    

     嵌套函数

    # #函数嵌套:用def声明
    # def foo():
    #     print('in the foo')
    #     def bar(): #具有局部变量的特性
    #         print('in the bar')
    #
    #     bar()
    #
    # foo()
    #
    # #函数调用
    # def test1():
    #     test2()
    #
    # test1()
    
    #作用域从内向外找,一层一层的找
    x=0
    def grandpa():
        def dad():
            x =2
            def son():
                x=3
                print(x)
            son()
        dad()
    grandpa()
    
  • 相关阅读:
    flutter 反序列化
    系统架构师-系统开发基础
    java Lambda表达式
    java异常
    HTTP缓存了解(一)
    设计模式(一):策略模式
    配置自己的ubuntu
    正则表达式:贪婪与非贪婪
    .htaccess文件
    mysql协议简析
  • 原文地址:https://www.cnblogs.com/xiaobai005/p/7905312.html
Copyright © 2011-2022 走看看