栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Python中,什么是全局语句?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Python中,什么是全局语句?

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

#file test.pymyvariable = 5  # myvariable has module-level scopedef func():    x = 3       # x has "local" or function level scope.

具有局部作用域的对象会在函数退出后立即死亡,并且永远无法检索(除非您拥有

return
它们),但是在函数内,您可以访问模块级作用域(或任何包含的作用域)中的变量:

myvariable = 5def func():    print(myvariable)  # prints 5def func2():    x = 3    def func3():        print(x)       # will print 3 because it picks it up from `func2`'s scope    func3()

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

myvariable = 5def func():    myvariable = 6     # creates a new "local" variable.   # Doesn't affect the global version    print(myvariable)  # prints 6func()print(myvariable)      # prints 5

现在,我们终于可以了

global
。该
global
关键字是你告诉蟒蛇,在你的函数特定变量是在全局(模块级)范围定义方式。

myvariable = 5def func():    global myvariable    myvariable = 6    # changes `myvariable` at the global scope    print(myvariable) # prints 6func()print(myvariable)  # prints 6 now because we were able         # to modify the reference in the function

换句话说,如果您使用关键字,则可以

myvariable
从内部更改module-scope中的值。
func``global


顺便说一句,合并范围可以任意深度嵌套:

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,不存在(易/干净)的方式来改变的值

x
在范围
func1
从内
func3
。这就是为什么
nonlocal
在python3.x中引入了关键字的原因。
nonlocal
的扩展,
global
它允许您修改从其他作用域中提取的变量,而不论该变量是从哪个作用域中提取的。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/441114.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号