Python变量状态保持四种方法
2024-08-28 20:19:09
Python状态保持
全局 global
def tester(start):
global state
state = start
def nested(label):
global state
print(label,state)
state += 1
return nested # 都声明为全局,只会保存一个副本,会覆盖
非本地 nonlocal
def tester(start):
state = start
def nested(label):
nonlocal state
print(label,state)
state += 1
return nested # Python3 主流 但是作用域只能是嵌套作用域
类 class
class nested():
def __init__(self,state):
self.state = state
def __call__(self,label):
print(self.state,label)
self.state += 1 # 有点老了
函数属性 函数名.变量名
def tester(start):
def nested(label):
print(label,nested.state)
nested.state += 1
nested.state = start
return nested # 未曾用过的黑魔法,这回就知道了
最新文章
- [LeetCode] Game of Life 生命游戏
- C# 中的委托和事件(转载)
- js 扩展Array支持remove方法
- bash操作小结
- 更加优雅地配置Spring Securiy(使用Java配置和注解)
- MyEclipse自动补全与快捷键设置
- 【缓存】Sql Server 2005/2008 SqlCacheDependency查询通知的使用总结
- linux语言环境设置
- jQuery查看dom元素上绑定的事件列表
- android在广播接收器BroadcastReceiver里面再进行发送广播,造成当前广播接收器不断循环执行问题
- Docker image 镜像介绍
- Android应用程序与SurfaceFlinger服务的关系概述和学习计划
- Linkedin工程师是如何优化他们的Java代码的(转)
- Python [目录]
- 使用kermit通过串口升级uboot
- day 21 内存管理,正则
- Linux 入门视频教程
- Spring Security Oauth2 示例
- C#闰年判断
- C++ main函数的参数