English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriales Básicos de Python

Control de Flujo de Python

Funciones en Python

Tipos de datos en Python

Operaciones de Archivos de Python

Objetos y Clases de Python

Fecha y Hora de Python

Conocimientos Avanzados de Python

Manual de Referencia de Python

Palabra clave Global en Python

在阅读本文之前,请确保您已掌握Python全局,局部和非局部变量的一些基础知识。

全局关键字简介

在Python中,global关键字允许您在当前作用域之外修改变量。它用于创建全局变量并在局部上下文中对该变量进行更改。

全局关键字规则

Python中global关键字的基本规则是:

  • 当我们在函数内部创建变量时,默认情况下它是局部的。

  • 当我们在函数外部定义变量时,默认情况下它是全局的。您不必使用global关键字。

  • 我们使用global关键字在函数内部读写全局变量。

  • 在函数外使用global关键字无效

全局关键字的使用(示例)

让我们举个实例。

Example1:从函数内部访问全局变量

c = 1 # 全局变量
def add():
    print(c)
add()

当我们运行上面的程序时,输出将是:

1

但是,在某些情况下,我们需要从函数内部修改全局变量。

Example2:从函数内部修改全局变量

c = 1 # 全局变量
    
def add():
    c = c + 2 # increment c by 2
    print(c)
add()

当我们运行上面的程序时,输出显示错误:

UnboundLocalError: local variable 'c' referenced before assignment

这是因为我们只能访问全局变量,而不能从函数内部对其进行修改。

解决方案是使用global关键字。

Example3:使用global从函数内部更改global变量

c = 0 # 全局变量
def add():
    global c
    c = c + 2 # increment by 2
    print("Inside add():", c)
add()
print("In main:", c)

当我们运行上面的程序时,输出将是:

Inside add(): 2
In main: 2

在上面的程序中,我们将c定义为add()函数内部的全局关键字。
然后,将变量c增加1,即c = c + 2。之后,我们调用该add()函数。最后,我们打印全局变量c。
如我们所见,函数之外的全局变量也发生了变化c = 2。

跨Python模块的全局变量

在Python中,我们创建一个模块config.py来保存全局变量,并在同一程序中的Python模块之间共享信息。

这是我们如何在python模块之间共享全局变量。

Example4:跨Python模块共享全局变量

创建一个config.py文件,以存储全局变量

a = 0
b = "empty"

Create an update.py file to change the global variable

import config
config.a = 10
config.b = "alphabet"

Create a main.py file to test the change of values

import config
import update
print(config.a)
print(config.b)

When we run the main.py file, the output will be

10
alphabet

In the above text, we create three files: config.py, update.py, and main.py.

The module config.py storesaandb'sglobal variables. In the update.py file, we import the config.py module and modifyaandbvalue. Similarly, in the main.py file, we import both the config.py and update.py modules. Finally, we print and test the value of the global variables, whether they have changed or not.

Global variables in nested functions

This is the method of using global variables in nested functions.

Example5: Using global variables in nested functions

def foo():
    x = 20
    def bar():
        global x
        x = 25
    
    print("Before calling bar: ", x)
    print("Immediate call to bar")
    bar()
    print("After calling bar: ", x)
foo()
print("x in the main body: ", x)

Output is:

Before calling bar:  20
Immediate call to bar
After calling bar:  20
x in the main body:  25

In the above program, we declare a global variable in the nested function bar(). In the foo() function, x has no effect on the global keyword.
Before and after calling bar, the variable x accepts the value of the local variable, that is, x =20. Outside the foo function, the variable x will take the value defined in the bar function, that is, x =25. This is because we used the global keyword in the bar function (local scope) to create a global variable.
If we make any changes in the bar() function, these changes will appear outside the local scope, that is, foo().