Python变量状态保持四种方法

本文介绍了Python中实现状态保持的几种方法,包括使用全局变量、非本地变量、类实例及函数属性等方式,并对比了它们的特点与适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python状态保持

​ 全局 global

1 def tester(start):
2     global state
3     state = start
4     def nested(label):
5         global state
6         print(label,state)
7         state += 1
8     return nested # 都声明为全局,只会保存一个副本,会覆盖
    

​ 非本地 nonlocal

1 def tester(start):
2     state = start
3     def nested(label):
4         nonlocal state
5         print(label,state)
6         state += 1
7     return nested # Python3 主流 但是作用域只能是嵌套作用域
       

​ 类 class

1 class nested():
2     def __init__(self,state):
3         self.state = state
4     def __call__(self,label):
5         print(self.state,label)
6         self.state += 1 # 有点老了

函数属性 函数名.变量名

1 def tester(start):
2     def nested(label):
3         print(label,nested.state)
4         nested.state += 1
5     nested.state = start
6     return nested  # 未曾用过的黑魔法,这回就知道了

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值