1、函数即变量2、高阶函数
a、把一个函数名当做实参创给另一个函数;
import time
def bar():
print('in the bar')
def test(func):
start_tmie=time.time()
func()
stop_time=time.time()
print('the func run time is %s'%(stop_time-start_tmie))
test(bar)
1
import time
2
def bar():
3
print('in the bar')
4
5
def test(func):
6
start_tmie=time.time()
7
func()
8
stop_time=time.time()
9
print('the func run time is %s'%(stop_time-start_tmie))
10
test(bar)
b、返回值包含函数名,不用修改函数的调用方式
import time
def bar():
time.sleep(3)
print("in the bar")
def test2(func):
print(func)
return func
bar=test2(bar)
bar()
1
import time
2
def bar():
3
time.sleep(3)
4
print("in the bar")
5
def test2(func):
6
print(func)
7
return func
8
bar=test2(bar)
9
bar()
函数嵌套
def test01():
print('in the test01')
def test02():
print('in the test02')
test02()
test01()
######打印结果#####
in the test01
in the test02
1
def test01():
2
print('in the test01')
3
def test02():
4
print('in the test02')
5
test02()
6
test01()
7
######打印结果#####
8
in the test01
9
in the test02
全局作用域和局部作用域
3、装饰函数
高阶函数+嵌套函数=装饰函数
# Aduthor:CCIP-Ma
import time
def timer(func):
def deco():
start_time=time.time()
func()
stop_time=time.time()
print('the time %s'%(stop_time-start_time))
return deco #返回门牌号,内存地址
@timer #test1=timer(test1) 意思一样
def test1():
time.sleep(3)
print('in the test1')
test1()
1
# Aduthor:CCIP-Ma
2
import time
3
def timer(func):
4
def deco():
5
start_time=time.time()
6
func()
7
stop_time=time.time()
8
print('the time %s'%(stop_time-start_time))
9
return deco #返回门牌号,内存地址
10
#test1=timer(test1) 意思一样
11
def test1():
12
time.sleep(3)
13
print('in the test1')
14
test1()