zoukankan      html  css  js  c++  java
  • Python的闭包

    什么是闭包

    #定义一个函数

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

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

  • 相关阅读:
    Mysql自定义函数总结
    MySQL的基本函数
    Mysql存储过程总结
    Mysql触发器总结
    Mysql索引总结(二)
    Mysql索引总结(一)
    Mysql游标使用
    别人的博客,留待后看
    mysql外键约束总结
    mysql视图总结
  • 原文地址:https://www.cnblogs.com/hujingnb/p/10181534.html
Copyright © 2011-2022 走看看