zoukankan      html  css  js  c++  java
  • 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))

  • 相关阅读:
    python小技巧之把list组合成chain
    airflow自动生成dag
    python之json读写
    Java写入的常用技巧(二)
    python并发——信号量
    python并发——进程间同步和通信
    python并发——从线程池获取返回值
    python获取hive表时间格式最大分区
    python递归获取目录下指定文件
    国际化(i18n)
  • 原文地址:https://www.cnblogs.com/sklhtml/p/9442030.html
Copyright © 2011-2022 走看看