python声明_在Python中什么是全局声明?

python中的每个“变量”都限于某个范围. python“文件”的范围是模块范围.考虑以下:

#file test.py

myvariable = 5 # myvariable has module-level scope

def func():

x = 3 # x has "local" or function level scope.

具有局部作用域的对象在函数退出后立即死亡,并且永远无法检索(除非您返回它们),但在函数内,您可以访问模块级作用域(或任何包含作用域)中的变量:

myvariable = 5

def func():

print(myvariable) # prints 5

def func2():

x = 3

def func3():

print(x) # will print 3 because it picks it up from `func2`'s scope

func3()

但是,您不能在该引用上使用赋值,并期望它将传播到外部作用域:

myvariable = 5

def func():

myvariable = 6 # creates a new "local" variable.

# Doesn't affect the global version

print(myvariable) # prints 6

func()

print(myvariable) # prints 5

现在,我们终于走向全球了. global关键字是告诉python函数中的特定变量在全局(模块级)范围内定义的方式.

myvariable = 5

def func():

global myvariable

myvariable = 6 # changes `myvariable` at the global scope

print(myvariable) # prints 6

func()

print(myvariable) # prints 6 now because we were able

# to modify the reference in the function

换句话说,如果使用global关键字,则可以在func中更改模块范围中myvariable的值.

另外,范围可以任意嵌套:

def func1():

x = 3

def func2():

print("x=",x,"func2")

y = 4

def func3():

nonlocal x # try it with nonlocal commented out as well. See the difference.

print("x=",x,"func3")

print("y=",y,"func3")

z = 5

print("z=",z,"func3")

x = 10

func3()

func2()

print("x=",x,"func1")

func1()

现在在这种情况下,没有变量在全局范围内声明,并且在python2中,没有(简单/干净)方法在func3中更改func1范围内的x值.这就是python3.x中引入nonlocal关键字的原因. nonlocal是global的扩展,允许您修改从另一个范围中提取的变量,无论其范围是什么.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值