闭包函数

def test(number):
    #在函数内部再定义一个函数,并且这个函数用到了外边函数的变量,那么将这个函数以及用到的一些变量称之为闭包
    def test_in(number_in):
        print("in test_in 函数, number_in is %d"%number_in)
        return number+number_in#使用到了外部的变量number
    return test_in #将内部函数作为返回值

#给test函数赋值,这个20就是给参数number
ret = test(20)#ret接收返回值(内部函数test_in)
#注意这里的100其实给参数number_in

print(ret(100)) #100+20
print(ret(200)) #200+20

def test1():
    print("----test1----")
test1()

ret = test1#使用对象引用函数,使用函数名进行传递
print(id(ret))

# 引用的对象地址和原函数一致
print(id(test1))
ret()

'''
----test1----
1511342483488
1511342483488
----test1----
'''

def line_conf(a,b):
    def line(x):
        return "%d * %d + %d"%(a,x,b)
    # 内部函数一定要使用外部函数,才能称为闭包函数
    return line

line_one = line_conf(1,1)
# 使用变量进行接收外部函数,然后使用变量进行调用闭包函数中的内部函数
line_two = line_conf(2,3)

print(line_one(7))
print(line_two(7))

'''
1 * 7 + 1
2 * 7 + 3
'''

2020-05-08

原文地址:https://www.cnblogs.com/hany-postq473111315/p/12847006.html