python核心编程之闭包
该文档仅用作学习笔记,转载请表明出处
函数调用
案例v15:
def test():
print("我被调用了!!")
test()
输出结果为:
我们简单试下如果调用的时候不加括号会发生什么。
案例v16:
def test():
print("我被调用了!!!")
test
print(test)
此时输出的结果为:
这个时候我们可以看出来,当我们单独使用函数名时,他仅仅类似于c语言的一个指针一样的功能。作用是指向函数所在的位置。
什么是闭包
案例v17:
#定义一个函数 函数名字叫test 返回test_in
def test(number):
#在test中再定义一个函数test_in 并且 在函数test_in 中使用了函数test中的变量
#那么就称之为闭包
def test_in(number_in):
print("in test_in 函数,number_in is %d"%number_in)
return number + number_in
return test_in
ret = test(20)
print(ret(100))
print(ret(200))
此时输出结果为:
这时候我们可以得到闭包的定义:
一个函数定义在另一个函数的定义体中,并且里面的函数调用了外面函数的变量,则统称为闭包。
我们简单看一下函数是怎么运行的。
案例v18:
#定义一个函数 函数名字叫test 返回test_in
def test(number):
#在test中再定义一个函数test_in 并且 在函数test_in 中使用了函数test中的变量
#那么就称之为闭包
print("1-------------------------------")
def test_in(number_in):
print("2-------------------------------")
print("in test_in 函数,number_in is %d"%number_in)
return number + number_in
print("3-------------------------------")
return test_in
ret = test(20)
print(ret)
输出结果是:
这时候我们可以看出来,内部函数实际上是没有执行的,只是将这个函数作为一个块当作返回值了而已。
闭包的实际应用
案例19:
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))
运行的结果为: