在 Python 中,我们可以在三种不同的作用域中声明变量:局部作用域、全局作用域和非局部作用域。
变量作用域指定了我们可以访问变量的区域。例如,
def add_numbers():
sum = 5 + 4
这里,sum 变量是在函数内部创建的,所以它只能在该函数内部访问(局部作用域)。这种类型的变量称为局部变量。
根据作用域,我们可以将 Python 变量分为三种类型
- 局部变量
- 全局变量
- 非局部变量
Python 局部变量
当我们在函数内部声明变量时,这些变量将具有局部作用域(在函数内部)。我们无法在函数外部访问它们。
这些类型的变量称为局部变量。例如,
def greet():
# local variable
message = 'Hello'
print('Local', message)
greet()
# try to access message variable
# outside greet() function
print(message)
输出
Local Hello NameError: name 'message' is not defined
这里,message 变量是 greet()
函数的局部变量,所以它只能在该函数内部访问。
这就是为什么当我们尝试在 greet()
函数外部访问它时会收到错误的原因。
为了解决这个问题,我们可以将名为 message 的变量设置为全局变量。
Python 全局变量
在 Python 中,在函数外部或全局作用域中声明的变量称为全局变量。这意味着全局变量可以在函数内部或外部访问。
让我们看一个在 Python 中如何创建全局变量的示例。
# declare global variable
message = 'Hello'
def greet():
# declare local variable
print('Local', message)
greet()
print('Global', message)
输出
Local Hello Global Hello
这次我们可以在 greet()
函数外部访问 message 变量。这是因为我们已经将 message 变量创建为全局变量。
# declare global variable
message = 'Hello'
现在,message 将可以在程序的任何作用域(区域)中访问。
Python 非局部变量
在 Python 中,nonlocal
关键字用于嵌套函数中,表示变量不属于内部函数的局部变量,而是属于外部函数的某个作用域。
这允许您在嵌套函数中修改外部函数的变量,同时仍将其与全局变量区分开来。
# outside function
def outer():
message = 'local'
# nested function
def inner():
# declare nonlocal variable
nonlocal message
message = 'nonlocal'
print("inner:", message)
inner()
print("outer:", message)
outer()
输出
inner: nonlocal outer: nonlocal
在上面的示例中,有一个嵌套的 inner()
函数。 inner()
函数定义在另一个函数 outer()
的作用域中。
我们使用了 nonlocal
关键字来修改嵌套函数中外部函数的 message
变量。
注意:如果我们更改非局部变量的值,更改将出现在局部变量中。
另请阅读