zoukankan      html  css  js  c++  java
  • 2019年2月23日 装饰器1:高阶函数,函数嵌套

     高阶函数

    定义:

    1函数接受的参数是一个函数名
    2函数返回值是一个函数
    3满足1与2任意一个,都称作高阶函数

    import time
    
    def test(func):
        #print(func) #打印内存地址
        start_time=time.time()
        func()
        stop_time=time.time()
        print('stop-start:%s'%(stop_time-start_time))
    
    def foo():
        time.sleep(1)
        print("foofoofoo")
    
    
    test(foo)
    def foo():
        print('from the foo')
    def test(func):
        return (func) #返回函数名
    
    res=test(foo)
    print(res)#返回foo的函数地址
    res() #运行foo()
    import time
    def foo ():
        time.sleep(2)
        print('from foo')
    
    def timer(func):
        start_time=time.time()
        func()
        stop_time=time.time()
        print('stop-start=%s'%(stop_time-start_time))
        return func#返回函数
    
    foo=timer(foo)#函数的传递
    foo()

    运行结果:

    from foo
    stop-start=2.0005898475646973
    from foo

    多运行一次func

     函数嵌套+闭包

    函数中又一次定义函数称作嵌套。

    def father(name):
        print('from father %s'%name)
        def son():
            print("from son")
            def grandson():
                print('from grandson')
            grandson()
        print(locals())#打印当前层的局部变量
        son()
    
    father("sxj")
  • 相关阅读:
    LeetCode-1-two-sum
    LeetCode-14-longest-common-prefix
    动态规划--矩阵链乘法
    动态规划--装配线调度算法
    LeetCode-9-palindrome-number
    LeetCode-8-string-to-integer-atoi
    LeetCode-7-Reverse Integer
    SElinux用户管理操作
    Minix3信号处理分析
    面对困难
  • 原文地址:https://www.cnblogs.com/python1988/p/10422430.html
Copyright © 2011-2022 走看看