python文件作用域是什么意思_Python中的作用域是什么

python中的作用域有4种:

搜索变量的优先级顺序依次是(LEGB):

作用域局部 > 外层作用域 > 当前模块中的全局 > python内置作用域。number = 10             # number 是全局变量,作用域在整个程序中

def test():

print(number)

a = 8               # a 是局部变量,作用域在 test 函数内

print(a)

test()

运行结果:10

8def 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

1num = 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 关键字。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值