python 中高阶函数和嵌套函数

 1、高阶函数:变量可以指向函数;

                        函数的参数可以接收变量;

                        一个函数可以接收另一个函数作为参数;

2、我们看下面实例

import time

def test1():
    time.sleep(3)#睡眠3秒
    print('this is test1')
    return test1


def test2(func):#func = test1
    print('this is test2')
    start_time = time.time() #开始的时间戳
    func()  #func() = test1()实际上是调用test1()
    end_time = time.time()#结束的时间戳
    print('this func is running %s' % (end_time-start_time))#这里是test1函数的运行时间
    return func #返回的其实是test1的内存地址

res = test2(test1)
print(res)

3、嵌套函数

        python程序,一个函数在另外一个函数的里面,外层的函数返回的是里层函数。也就是函数本身被返回了,返回的是函数(听起来和C语言的一些东东相似)。

下面我们看一个简单的嵌套函数:

def test1():
    def test2():
        print('this is test2')

如何调用呢?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章