1.函数引用
def Test():
print("---Test Fun---")
python中函数名和C、C++等语言中的函数指针类似,Python函数名称为函数代码块的指针。
2.闭包
#定义一个函数
def TestFun(number):
#在函数内部在定义一个函数,并且这个函数用到了外边函数的变量
number_in = number + 100;
print(number_in)
def Test_in(number_in):
print("Test_in=>%d"%number_in)
return number + number_in
return Test_in
ret = TestFun(100)
print(ret(20))
print(ret(30))
out:
200
Test_in=>20
120
Test_in=>30
130
def counter(start=0):
count = [start]
print(count)
def incr():
print(count[0])
count[0]+=1
return count[0]
return incr
c1 = counter(5)
print(c1())
print(c1())
out:
[5]
5
6
6
7
#nonlocal访问外部函数的局部变量
def counter(start=0):
def incr():
nonlocal start
start += 1
return start
return incr
c1 = counter(5)
print(c1())
print(c1())
c2 = counter(50)
print(c2())
print(c2())
print(c1())
print(c1())
print(c2())
print(c2())
out:
6
7
51
52
8
9
53
54