首页 > 编程语言 > 详细

python 闭包

时间:2018-08-08 12:39:38      阅读:133      评论:0      收藏:0      [点我收藏+]

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))

技术分享图片

python 闭包

原文:https://www.cnblogs.com/sklhtml/p/9442030.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!