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")
  • 相关阅读:
    Python格式化输出
    每天写点shell脚本 (持续更新)
    linux limits.conf 配置
    ELK 日志分析系统
    开源大数据处理工具
    glusterFS分布式存储部署流程
    glusterFS的部署流程
    parted命令详解
    /proc文件系统
    /proc文件系统(二):/proc/<pid>/stat
  • 原文地址:https://www.cnblogs.com/python1988/p/10422430.html
Copyright © 2011-2022 走看看