加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python的闭包

发布时间:2020-12-17 00:24:51 所属栏目:Python 来源:网络整理
导读:什么是闭包 #定义一个函数 def test(number): #在函数内部再定义一个函数,并且这个函数用到了外边函数的变量,那么将这个函数以及用到的一些变量称之为闭包 def test_in(number_in): print("in test_in 函数,number_in is %d"%number_in) return number+num

什么是闭包

#定义一个函数

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就是给参数

numberret = test(20)#注意这里的100其实给参数

number_inprint(ret(100))#注意这里的200其实给参数

number_inprint(ret(200))

运行结果:

in test_in 函数,number_in is 100

120

in test_in 函数,number_in is 200

220

内部函数对外部函数作用域里变量的引用(非全局变量),则称内部函数为闭包。

理解闭包

def counter(start=0):

  count=[start]

  def incr():

    count[0] += 1

    return count[0]

  return incr

c1=counter(5)

print(c1())

print(c1())

c2=counter(100)

print(c2())

print(c2())

运行结果

6

7

101

102

函数返回给变量后,函数不会释放,当改变函数中的变量是,下次调用依旧是这个变量

使用nonlocal访问外部函数的局部变量(python3)

def counter(start=0):

  def incr():

    nonlocal start

    start += 1

    return start

  return incr

c1 = counter(5)

print(c1())

print(c1())

闭包在实际中的使用

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

相当于先设定好变量值,当使用的时候就可以直接传递关注的参数就可以了

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读