python 闭包

def test():
  # 函数名中的test相当于一个变量名
  print('------1-------')


# test() #调用这个函数 ------1-------

# # test #test指向了一个函数块,变量名指向了函数体

# print(test) # <function test at 0x000002BD550C7F28>


# b = test

# print(b) # <function test at 0x000002BD550C7F28>

# b() # ------1-------

 

 

# 什么是闭包?
def testTest(number):

  # 在函数内部在定义一个函数,并且这个函数用到了外边函数的变量,那么将这个函数以及用到的一些变量统称为闭包
  def test_in(number_in):
    print("in test_in 函数,number_in in is %d"%number_in)
    return numbner_in + number
  # 其实这里就是返回的就是闭包的结果
  return test_in

ret = testTest(20)


def num(number):
  print('---------1--------')

  def num_in(number_in):
    print('---------2--------')
    print(number+number_in)

  print('---------3--------')

  return num_in


ret = num(20)
print('----------------------------'*2)
ret(10)
ret(20)

 

# 闭包的应用

def line_conf(a,b):
  def line(x):
    return a*x + b
  return line

line1 = line_conf(1,1)
line2 = line_conf(4,5)\


# line1 保存的line_conf中的变量,并且拥有了line()函数

print(line1(5))
print(line2(5))

print(line1(0))

posted @ 2018-08-08 12:07  红尘陌上,独自行走  阅读(90)  评论(0编辑  收藏  举报