Python闭包的使用

 时间:2024-10-12 00:27:48

1、这里使用Ubuntu系统做一个小例子演示,登录Ubuntu系统,打开终端,输入python3进入python交互环境

Python闭包的使用

2、在交互环境,定义一个函数,具体代码如下;>>> def test():... print ('test')...>>> test<function test at 0x7f6b36fc6ea0>单独test打印出的是函数的地址,函数并没有执行

Python闭包的使用

3、在交互环境继续执行代码如下:>>> def test():... print ('test')...>>> test<function test at 0x7f42187dfea0>>>> f = test f就是test函数的地址,f()同样可以调用这个函数>>> f()test这有点类似c++语言函数指针的概念,但是使用要简单很多

Python闭包的使用

4、了解了上面的概念,新建一个‘test.py’文件测试闭包vim test.py

Python闭包的使用

5、在‘test.py’文件写代码如下:1 def test(number1): 2 print ('testin start') 3 def testin(): 4 print ('testin start') 5 print (number1+1) 6 7 return testin 8 test(100)

Python闭包的使用

6、保存退出,运行test.pypython3 test.py发现testin并没有运行,因为并没有调用,test返回testin函数地址

Python闭包的使用

7、重新打开‘test.py’更改代码如下:def test(number1): print ('test start') def testin(): print ('testin start') print (number1+1) return testina = test(100)print (a())

Python闭包的使用

8、保存退出,运行test.pypython3 test.pytestin也执行了

Python闭包的使用
  • python里简单理解闭包的作用
  • 面试题谈什么是Python闭包
  • JavaScript作用域和闭包
  • 如何使用JavaScript闭包循环生成数组元素
  • 通过示例彻底搞懂js闭包
  • 热门搜索
    已妥投是什么意思 圆脸适合什么短发 官家是什么意思 bd是什么 嘴边长痘痘是什么原因 bank是什么意思 mad是什么意思 program files是什么意思 ad是什么 耵聍是什么