python中的作用域有4种:
搜索变量的优先级顺序依次是(LEGB):
作用域局部 > 外层作用域 > 当前模块中的全局 > python内置作用域。
number = 10 # number 是全局变量,作用域在整个程序中 def test(): print(number) a = 8 # a 是局部变量,作用域在 test 函数内 print(a) test()
运行结果:
10 8
def outer(): o_num = 1 # enclosing i_num = 2 # enclosing def inner(): i_num = 8 # local print(i_num) # local 变量优先 print(o_num) inner() outer()
运行结果:
8 1
num = 1 def add(): num += 1 print(num) add()
运行结果:
UnboundLocalError: local variable 'num' referenced before assignment
相关推荐:《Python视频教程》
如果想在函数中修改全局变量,需要在函数内部在变量前加上global关键字。
num = 1 # global 变量 def add(): global num # 加上 global 关键字 num += 1 print(num) add()
运行结果:
2
同理,如果希望在内层函数中修改外层的 enclosing 变量,需要加上 nonlocal 关键字
def outer(): num = 1 # enclosing 变量 def inner(): nonlocal num # 加上 nonlocal 关键字 num = 2 print(num) inner() print(num) outer()
运行结果:
2 2
另外我们需要注意的是:
1.只有模块、类、及函数才能引入新作用域;
2.对于一个变量,内部作用域先声明就会覆盖外部变量,不声明直接使用,就会使用外部作用域的变量(这时只能查看,无法修改);
3.如果内部作用域要修改外部作用域变量的值时, 全局变量要使用 global 关键字,嵌套作用域变量要使用 nonlocal 关键字。
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 模板不会安装或需要功能定制以及二次开发?
发表评论
还没有评论,快来抢沙发吧!