码Python代码时,想用全局变量,报了错。所以上网查了相关文档,总结出 以下几点 :
代码段_0:
num = 100
def show(value):
print 'id = %s' % id(value)
def func_0():
temp = num
show(temp)
def func_1():
global num
show(num)
show(num)
func_0()
func_1()
Output:
id = 30312368
id = 30312368
id = 30312368
Process finished with exit code 0
代码段_1:
num = 100
def show(value):
print 'id = %s' % id(value)
def func_0():
temp = num
show(temp)
def func_1():
num += 1
show(num)
show(num)
func_0()
func_1()
Output:
Traceback (most recent call last):
id = 28153776
File "/home/user/Desktop/temp.py", line 20, in <module>
id = 28153776
func_1()
File "/home/user/Desktop/temp.py", line 14, in func_1
num += 1
UnboundLocalError: local variable 'num' referenced before assignment
Process finished with exit code 1
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有