您的位置:首页 > 编程语言 > Python开发

Python变量的作用范围

2018-03-24 19:52 260 查看

Python变量的作用范围

全局变量

在函数外部定义的,可以在该变量后面任何地方调用该变量,那么这个变量就是全局变量。如果不加显示声明,全局与局部变量同名时,全局变量会被隐藏,这和C++类似。

局部变量

在代码段内部定义的变量,与C++一样的。

全局变量与局部变量共存的情况

x = "global"

def foo():
global x
y = "local"
x = x * 2
print(x)  # global global
print(y)  # local

foo()


x = 5

def foo():
x = 10
print("local x:", x)  # local x: 10

foo()
print("global x:", x)  # global x: 5


非局部变量

非局部变量用于局部作用范围没有确定的内嵌函数中。这意味着这个变量不在局部和全局范围中。使用
nolocal
定义:

def outer():
x = "local"

def inner():
nonlocal x
x = "nonlocal"
print("inner:", x)

inner()
print("outer:", x)

outer()


输出:

inner: nonlocal
outer: nonlocal


上面的代码意味着,定义了一个内嵌函数,同时在下面又要执行内嵌函数,但是不想使用全局的变量。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: