闭包函数:
# 用闭包函数计算当x=20,y=200,z=1000时,fun1=x + 2*y + 3*z的函数值 def a(x): def b(y): def c(z): return x + 2*y + 3*z return c return b print(a(20)(200)(1000))
# 用闭包函数计算一元一次线性方程的值 def line_conf(a, b): def line(x): return a*x + b return line line1 = line_conf(1, 1) line2 = line_conf(4, 5) print(line1(5)) print(line2(5)) print(line_conf(2,3)(5))
#定义一个函数 def test(number): #在函数内部再定义一个函数,并且这个函数用到了外边函数的变量,那么将这个函数以及用到的一些变量称之为闭包 def test_in(number_in): print("in test_in 函数, number_in is %d"%number_in) return number+number_in #其实这里返回的就是闭包的结果 return test_in #给test函数赋值,这个20就是给参数number test_in = test(20) print(id(test_in)) print(id(test)) #注意这里的100其实给参数number_in print(test_in(100)) #注意这里的200其实给参数number_in print(test_in(200)) print(test(20)(200))
修改外部参数
python3的做法:
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())
python2的做法
def counter(start=0): count=[start] def incr(): count[0] += 1 return count[0] return incr c1 = counter(5) print(c1())#6 print(c1())#7 c2 = counter(100) print(c2())#101 print(c2())#102
利用这一原理,做计数函数。
def counter(start=0): def addone(): nonlocal start start += 1 return start return addone c1 = counter(0) print(c1()) print(c1()) print(c1()) print(c1())