Python函数中的变量作用域是如何工作的
在本文中,我们将讨论Python函数中变量作用域的工作方式。
名称的作用域是程序中您可以明确访问名称(例如变量)的区域。
因此,变量作用域是我们可以访问变量的区域,如以下示例所示 –
def multiplication():
product = 7*9
在这里,“product”变量是在函数内部创建的,因此它只能在函数内部访问。
一般来说,Python的作用域概念使用LEGB规则来进行解释,LEGB是基于变量作用域的四个主要类别。它代表 –
- Local(局部)
-
Enclosing(嵌套)
-
Global(全局)
-
Built-in(内置)。
让我们逐个讨论所有的作用域。
局部作用域
当变量在函数内部定义时,它的作用域被限制在函数内部。它存在于函数运行的时间内(源码)并且从定义到函数结束的时间段内都可用。这意味着它的值甚至无法从函数外部访问。
示例
以下是局部作用域变量的示例 –
def prime_numbers():
first_prime_no = 2
print("The first prime number is: ", first_prime_no)
# the driver code
prime_numbers()
print("The first prime number is: ", first_prime_no)
输出
通过使用”prime numbers()”函数,我们能够打印出”第一个素数”变量的值。然而,当试图从函数外部读取并打印同一个变量时,会引发NameError异常。因为”第一个素数”变量是函数的”局部变量”,无法从函数体外访问,如下面的输出所示:
The first prime number is: 2
Traceback (most recent call last):
File "C:\Users\Lenovo\Desktop\untitled.py", line 6, in <module>
print("The first prime number is: ", first_prime_no)
NameError: name 'first_prime_no' is not defined
全局范围
可能这是最简单的作用域学习。当一个变量在任何函数外定义时,它变成一个全局变量,并且它的作用域在整个程序中任何地方都可以使用。这意味着它可以在任何函数内使用。此外,我们可以修改全局变量的值。
示例
以下是一个全局作用域变量的示例 –
animal = "Lion"
def animal_species():
pantheria = "Pantheria"
print('The name and species of the animal is:',animal, pantheria)
def animal_kingdom(name):
print('The name and kingdom of the animal is:',animal, name)
animal_species()
animal_kingdom("Animalia")
输出
以下是上述代码的输出 –
The name and species of the animal is: Lion Pantheria
The name and kingdom of the animal is: Lion Animalia
封闭范围
一个特殊的范围,仅在嵌套函数中可用,叫做封闭(或非局部)范围。封闭范围是外部或封闭函数的范围,如果局部范围是一个内部或嵌套函数的话。您在封闭函数中定义的名称包含在该范围内。
示例
在示例代码的’Lion()’函数中,变量’species’被使用。在这种情况下,它既不是局部范围也不是全局范围。术语”封闭范围”指的是这个。
def animal():
species = "Pantheria"
def Lion():
kingdom= "Animalia"
print('The species of the animal is:', species)
print('The kingdom of the animal is:',kingdom)
Lion()
animal()
输出
以下是上述代码的输出 –
The species of the animal is: Pantheria
The kingdom of the animal is: Animalia
内置作用域
在Python中,内置作用域具有最广泛的范围。Python中自带的每个模块中的保留名称都有自己的内置作用域。当无法在局部、封闭或全局作用域中找到标识符时,Python会搜索内置作用域来确定其是否已在那里定义。
Python首先检查局部作用域以验证哪些变量在那里定义,然后是封闭作用域,最后是全局作用域。如果在任何地方都找不到标识符,则会最后检查内置作用域。
示例
在这种情况下,函数int()、print()和type()不需要在此处定义,因为它们已在Python的内置作用域中定义-
x = 17.89
int(x)
print('The value of x is:',x)
print('The type of x is:',type(x))
输出
以下是上述代码的输出 –
The value of x is: 17.89
The type of x is: <class 'float'>
在Python中的全局变量关键字
通过使用global关键字,您可以指示Python使用全局声明的变量而不是在本地创建变量。只需输入”global”和变量名来利用该关键字。
示例
下面是一个在Python中使用global关键字的示例-
animal = "Lion"
def animal_species(Pan):
global animal
animal = Pan
def animal_kingdom():
animalia = "Animalia"
print('The animal species and kingdom is:',animal,animalia)
animal_species('Pantheria')
animal_kingdom()
输出
既然我们已经看到了,我们可以说我们希望通过使用全局关键字来使用在全局作用域中定义的变量”animal”。因此,当我们将值”Pan”赋给变量时,我们在函数外部改变了它的值。
The animal species and kingdom is: Pantheria Animalia
示例
以下是在Python中使用global关键字的示例 –
animal = "Lion"
def animal_name():
animal = "Panther"
print('The animal is:',animal)
animal_name()
print ('The animal is:',animal)
输出
上面的代码将打印出”Panther”和”Lion”的值,因为在局部作用域变量中”animal”指向”Panther”,而在method()函数外部指向全局变量。
The animal is: Panther
The animal is: Lion
Python中的nonlocal关键字
nonlocal是用于嵌套函数中的一个有用的关键字。这个关键字会引用最近的封闭作用域中之前绑定的变量作为结果。换句话说,它会阻止变量首先尝试在本地绑定,并将其推到上一级。与global关键字一样,语法相同。
示例
在下面的示例中,”animal”在函数”animal kingdom()”中引用一个”本地变量”,在方法”animal name()”中引用一个”非本地变量”,并且在这些函数外部引用一个”全局变量”。现在使用了”非本地变量”。
animal = "Lion-global variable"
def animal_name():
animal = "Panther-nonlocal variable"
def animal_kingdom():
nonlocal animal
animal = "Animalia-local variable"
print('The animal is:',animal)
animal_kingdom()
print('The animal is:',animal)
animal_name()
print ('The animal is:',animal)
输出
在函数“animal kingdom()”中,我们使用了关键字“nonlocal”来引用“animal”变量。因此,当我们修改非局部变量“animal”的值时,它也会改变在方法函数“animal name()”中定义的值。
The animal is: Animalia-local variable
The animal is: Animalia-local variable
The animal is: Lion-global variable