Python 简明教程

Python Variable Scope

Python中的 scope of a variable 被定义为用户可以访问变量的特定区域或区域。变量的作用域取决于其定义的位置和方式。在 Python 中,变量可以具有全局作用域或局部作用域。

The scope of a variable in Python is defined as the specific area or region where the variable is accessible to the user. The scope of a variable depends on where and how it is defined. In Python, a variable can have either a global or a local scope.

Types of Scope for Variables in Python

根据作用域,Python变量分为三类 −

On the basis of scope, the Python variables are classified in three categories −

  1. Local Variables

  2. Global Variables

  3. Nonlocal Variables

Local Variables

局部变量在特定函数或代码块中定义。它只能被其定义的函数或块访问,并且具有有限的作用域。换句话说,局部变量的作用域仅限于其定义的函数,如果尝试在此函数之外访问它们,则会导致错误。请务必记住,可以有多个同名的局部变量。

A local variable is defined within a specific function or block of code. It can only be accessed by the function or block where it was defined, and it has a limited scope. In other words, the scope of local variables is limited to the function they are defined in and attempting to access them outside of this function will result in an error. Always remember, multiple local variables can exist with the same name.

Example

以下示例显示了局部变量的作用域。

The following example shows the scope of local variables.

def myfunction():
   a = 10
   b = 20
   print("variable a:", a)
   print("variable b:", b)
   return a+b

print (myfunction())

在上述代码中,我们通过其函数访问了局部变量。因此,代码会产生以下输出 -

In the above code, we have accessed the local variables through its function. Hence, the code will produce the following output −

variable a: 10
variable b: 20
30

Global Variables

全局变量可以从程序的任何部分访问,并且在任何函数或代码块外定义。它不特定于任何块或函数。

A global variable can be accessed from any part of the program, and it is defined outside any function or block of code. It is not specific to any block or function.

Example

以下示例显示了全局变量的作用域。我们可以在函数作用域的内部和外部访问它们。

The following example shows the scope of global variable. We can access them inside as well as outside of the function scope.

#global variables
name = 'TutorialsPoint'
marks = 50
def myfunction():
   # accessing inside the function
   print("name:", name)
   print("marks:", marks)
# function call
myfunction()

以上代码将生成以下输出 −

The above code will produce the following output −

name: TutorialsPoint
marks: 50

Nonlocal Variables

未在局部或全局作用域中定义的 Python 变量称为非局部变量。它们在嵌套函数中使用。

The Python variables that are not defined in either local or global scope are called nonlocal variables. They are used in nested functions.

Example

以下示例演示了非局部变量的工作方式。

The following example demonstrates the how nonlocal variables works.

def yourfunction():
   a = 5
   b = 6
   # nested function
   def myfunction():
      # nonlocal function
      nonlocal a
      nonlocal b
      a = 10
      b = 20
      print("variable a:", a)
      print("variable b:", b)
      return a+b
   print (myfunction())
yourfunction()

上述代码会产生以下输出 -

The above code will produce the below output −

variable a: 10
variable b: 20
30

Namespace and Scope of Python Variables

名称空间是标识符的集合,例如变量名称、函数名称、类名称等。在 Python 中,名称空间用于管理变量的作用域并防止命名冲突。

A namespace is a collection of identifiers, such as variable names, function names, class names, etc. In Python, namespace is used to manage the scope of variables and to prevent naming conflicts.

Python 提供以下类型的命名空间 −

Python provides the following types of namespaces −

  1. Built-in namespace contains built-in functions and built-in exceptions. They are loaded in the memory as soon as Python interpreter is loaded and remain till the interpreter is running.

  2. Global namespace contains any names defined in the main program. These names remain in memory till the program is running.

  3. Local namespace contains names defined inside a function. They are available till the function is running.

这些名称空间嵌套在彼此内部。下图显示了名称空间之间的关系。

These namespaces are nested one inside the other. Following diagram shows relationship between namespaces.

types of namespace

特定变量的生命周期仅限于其定义所在的名称空间中。因此,无法从任何外部名称空间访问存在于内部名称空间中的变量。

The life of a certain variable is restricted to the namespace in which it is defined. As a result, it is not possible to access a variable present in the inner namespace from any outer namespace.

Python globals() Function

Python 的标准库包含了一个内置函数 globals()。它会返回一个在全局名称空间中当前可用的符号字典。

Python’s standard library includes a built-in function globals(). It returns a dictionary of symbols currently available in global namespace.

直接从 Python 提示符运行 globals() 函数。

Run the globals() function directly from the Python prompt.

>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}

可以看出,包含所有内置函数和内置异常定义的内置模块已加载。

It can be seen that the built-in module which contains definitions of all built-in functions and built-in exceptions is loaded.

Example

保存以下代码,其中包含少量变量以及一个包含少量其他变量的函数。

Save the following code that contains few variables and a function with few more variables inside it.

name = 'TutorialsPoint'
marks = 50
result = True
def myfunction():
   a = 10
   b = 20
   return a+b

print (globals())

从此脚本内部调用 globals() 会返回以下字典对象 −

Calling globals() from inside this script returns following dictionary object −

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000263E7255250>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\user\\examples\\main.py', '__cached__': None, 'name': 'TutorialsPoint', 'marks': 50, 'result': True, 'myfunction': <function myfunction at 0x00000263E72004A0>}

全局名称空间现在包含程序中的变量和它们的值以及其中的函数对象(而不是函数中的变量)。

The global namespace now contains variables in the program and their values and the function object in it (and not the variables in the function).

Python locals() Function

Python 的标准库包含一个内置函数 locals()。它返回一个字典,其中包含函数局部名称空间中当前可用的符号。

Python’s standard library includes a built-in function locals(). It returns a dictionary of symbols currently available in the local namespace of the function.

Example

修改上述脚本,以便从函数内部打印全局和局部名称空间的字典。

Modify the above script to print dictionary of global and local namespaces from within the function.

name = 'TutorialsPoint'
marks = 50
result = True
def myfunction():
   a = 10
   b = 20
   c = a+b
   print ("globals():", globals())
   print ("locals():", locals())
   return c
myfunction()

输出显示 locals() 返回一个字典,其中包含函数中当前可用的变量及其值。

The output shows that locals() returns a dictionary of variables and their values currently available in the function.

globals(): {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000169AE265250>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\mlath\\examples\\main.py', '__cached__': None, 'name': 'TutorialsPoint', 'marks': 50, 'result': True, 'myfunction': <function myfunction at 0x00000169AE2104A0>}
locals(): {'a': 10, 'b': 20, 'c': 30}

由于 globals() 和 locals 函数都会返回字典,因此你可以使用字典的 get() 方法或索引运算符从各自的名称空间访问变量的值。

Since both globals() and locals functions return dictionary, you can access value of a variable from respective namespace with dictionary get() method or index operator.

print (globals()['name']) # displays TutorialsPoint
print (locals().get('a')) # displays 10

Namespace Conflict in Python

如果在全局和局部作用域都存在一个同名变量,Python 解释器会优先考虑局部名称空间中的那个。

If a variable of same name is present in global as well as local scope, Python interpreter gives priority to the one in local namespace.

Example

在以下示例中,我们定义了一个局部变量和一个全局变量。

In the following example, we define a local and a global variable.

marks = 50 # this is a global variable
def myfunction():
   marks = 70 # this is a local variable
   print (marks)

myfunction()
print (marks) # prints global value

它将生成如下输出:

It will produce the following output −

70
50

Example

如果尝试从函数内部操作全局变量的值,Python 会引发 UnboundLocalError ,如下面的示例所示 -

If you try to manipulate value of a global variable from inside a function, Python raises UnboundLocalError as shown in example below −

# this is a global variable
marks = 50
def myfunction():
   marks = marks + 20
   print (marks)

myfunction()
# prints global value
print (marks)

它会产生以下错误消息 -

It will produce the following error message −

   marks = marks + 20
           ^^^^^
UnboundLocalError: cannot access local variable 'marks' where it is not associated with a value

Example

要修改全局变量,你可以通过字典语法进行更新,或使用 global 关键字在修改之前引用它。

To modify a global variable, you can either update it with a dictionary syntax, or use the global keyword to refer it before modifying.

var1 = 50 # this is a global variable
var2 = 60 # this is a global variable
def myfunction():
   "Change values of global variables"
   globals()['var1'] = globals()['var1']+10
   global var2
   var2 = var2 + 20

myfunction()
print ("var1:",var1, "var2:",var2) #shows global variables with changed values

执行代码后,它会产生以下输出 -

On executing the code, it will produce the following output −

var1: 60 var2: 80

Example

最后,如果你尝试在全局作用域中访问局部变量,Python 会引发 NameError,因为局部作用域中的变量不能在外部访问。

Lastly, if you try to access a local variable in global scope, Python raises NameError as the variable in local scope can’t be accessed outside it.

var1 = 50 # this is a global variable
var2 = 60 # this is a global variable
def myfunction(x, y):
   total = x+y
   print ("Total is a local variable: ", total)

myfunction(var1, var2)
print (total) # This gives NameError

它会产生以下错误消息 -

It will produce the following error message −

Total is a local variable: 110
Traceback (most recent call last):
   File "C:\Users\user\examples\main.py", line 9, in <module>
   print (total) # This gives NameError
          ^^^^^
NameError: name 'total' is not defined