标签:代码 too global 效果 用法 现象 注意 var 全局变量
Python 中,一个变量的作用域总是由在代码中被赋值的地方所决定的。
hehe=6
def f():
print(hehe)
f()
print(hehe)
上述代码可以正常运行且输出为6和6
hehe=6
def f():
print(hehe)
hehe=2
f()
print(hehe)
抛出的错误信息为:
hehe=6
def f():
hehe=2
print(hehe)
f()
print(hehe)
上述输出是2和6,也即f函数中print使用的是局部变量hehe,而最后一个print语句使用的全局hehe。
hehe=6
def f():
global hehe
print(hehe)
hehe=3
f()
print(hehe)
在用global修饰符声明hehe是全局变量的hehe后(注意,global语句不允许同时进行赋值如global hehe=3是不允许的),上述输出是6和3,得到了我们想要的效果。
标签:代码 too global 效果 用法 现象 注意 var 全局变量
原文地址:https://www.cnblogs.com/xiaohuhu/p/9130791.html