装饰器2 高阶函数 函数嵌套 闭包

 高阶函数定义
1.函数接受的参数是一个函数名

2.函数的返回值是一个函数名

3.满足上诉条件任意一个,都可称之为高阶函数

1 def test():
2     print('你好啊')
3 def high_func(func):
4     print('高阶函数')
5     func()
6 high_func(test)
7 输出:
8 高阶函数
9 你好啊

函数嵌套    在函数里面在定义一个函数

 1 def father(name):
 2     print('from father %s' % name)
 3     def son():
 4         print('from son')
 5         def dahghter():
 6             print('from daughter')
 7         dahghter()
 8     son()
 9 father('a')
10 输出:
11 from father a
12 from son
13 from daughter

闭包:在一个作用域里放入定义变量,相当于打了一个包

1 def test(name):
2     def son():
3         def grandson():
4             print('我的名字是%s'% name)
5         grandson()
6     son()
7 test('小明')
8 输出:
9 我的名字是小明

闭包的基本实现

 1 import time
 2 def timmer(func):
 3     def wrapper():
 4         start_time = time.time()
 5         func()
 6         stop_time = time.time()
 7         print('程序运行时间%s'%(stop_time-start_time))
 8     return wrapper
 9 def fool():
10     time.sleep(3)
11     print('程序运行完了')
12 f = timmer(fool)
13 f()
14 fool = timmer(fool)
15 fool()
16 输出:
17 程序运行完了
18 程序运行时间3.0032291412353516
19 程序运行完了
20 程序运行时间3.003220796585083

添加装饰器@timmer  结果

 1 import time
 2 def timmer(func):
 3     def wrapper():
 4         start_time = time.time()
 5         func()
 6         stop_time = time.time()
 7         print('程序运行时间%s'%(stop_time-start_time))
 8     return wrapper
 9 @timmer  # 相当于 fool = timmer(fool)
10 def fool():
11     time.sleep(3)
12     print('程序运行完了')
13 # f = timmer(fool)
14 # f()
15 # fool = timmer(fool)
16 # fool()
17 fool()
18 输出:
19 程序运行完了
20 程序运行时间3.0024335384368896

语法糖@             语法糖表示既好看又好用的语法

原文地址:https://www.cnblogs.com/ch2020/p/12375034.html