python 内嵌函数, 闭包, 函数装饰器
2024-08-26 22:09:04
一. 函数内嵌 闭包
- 在python中,函数可以作为返回值, 可以给变量赋值.
- 在python中, 内置函数必须被显示的调用, 否则不会执行.
#!/usr/bin/env python
#-*- coding: utf-8 -*- def foo():
m = 4
def bar():
n = 3
d = m + n
return d
return bar test = foo()
print test() #结果:
7#!/usr/bin/env python
#-*- coding: utf-8 -*- def foo():
m = 4
def bar():
n = 3
m = m + n
return m
return bar test = foo()
print test() #结果
UnboundLocalError: local variable 'm' referenced before assignment 在python2中 把m换成list就不会出现这样的错误, 在python3中,nonlocal 可以解决这个问题, 没搞清楚其中的原理
二、嵌套函数和它的变种(装饰器)
以下两端代码,作用是相同的,
def test(n):
return n def test_pro(func):
y = 100
def warpper(x):
return func(y) * x return warpper f = test_pro(test)
print f(4) #结果
400
将上边代码改写:
def test_pro(func):
y = 100
def warpper(x):
return func(y) * x return warpper @test_pro
def test(n):
return n print test(4) #结果
400
最新文章
- Java 部分注意160530
- ubuntu系统下配置php支持SQLServer数据库
- bzoj 3131 [Sdoi2013]淘金(数位DP+优先队列)
- MySQL数据库中日期中包涵零值的问题
- J2EE之普通类载入web资源文件的方法
- POJ 2352 &;amp;&;amp; HDU 1541 Stars (树状数组)
- 使用vue-axios请求geoJson数据报错的问题
- 简单工厂模式demo
- 新浪实时股票数据接口http://hq.sinajs.cn/list=股票代码
- java的static与C#的static的异同
- Django认证系统auth认证
- 分布式缓存技术redis系列(四)——redis高级应用(集群搭建、集群分区原理、集群操作)
- Rancher + k8s + docker 部署资料
- 解决Maven build 慢的问题
- DAX/PowerBI系列 - 参数表(Parameter Table) - 大客户分析(Top N)
- 将本地 项目文件托管到 github
- GET、POST编码问题
- thinkphp调整框架核心目录think的位置
- solve the promble of VMware Workstation Ubuntu18.04 ethernet interface losting
- 【转】MySQL数据表中记录不存在则插入,存在则更新