English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet article, vous découvrirez les variables globales, locales, non locales en Python et où les utiliser.
Dans Python, les variables déclarées en dehors d'une fonction ou dans un domaine global sont appelées variables globales. Cela signifie qu'elles peuvent être accédées à l'intérieur ou à l'extérieur d'une fonction.
Let's see an example of how to create a global variable in Python.
x = "global" def foo(): print("intérieur x:", x) foo() print("extérieur x:", x)
When we run the code, the output will be:
intérieur x: global extérieur x: global
Dans le code ci-dessus, nous avonsxcréé en tant que variable globale et définissant foo() pour imprimer la variable globalex。Enfin, nous appelons foo() pour imprimerxla valeur.
Si vous souhaitez modifierxla valeur.
x = "global" def foo(): x = x * 2 print(x) foo()
When we run the code, the output will be:
Si vous souhaitez modifier
Que faire de la valeur ?
Pour réaliser cette fonctionnalité, nous avons utilisé le mot-clé global. Pour plus d'informations, veuillez visiterMots-clés globaux Python。
Les variables déclarées à l'intérieur d'une fonction ou dans un domaine local sont appelées variables locales.
def foo(): y = "local" foo() print(y)
When we run the code, the output will be:
NameError: le nom 'y' n'est pas défini
La sortie affiche une erreur car nous essayons d'accéder à une variable locale y dans le domaine global, tandis que la variable locale ne fonctionne que dans foo() ou dans un domaine local.
Voyons un exemple de comment créer une variable locale en Python.
Généralement, nous déclarons une variable à l'intérieur d'une fonction pour créer une variable locale.
def foo(): y = "local" print(y) foo()
Lorsque nous exécutons le code, il affichera :
local
Voyonsle problème précédent,oùxest une variable globale, que nous voulons modifier à l'intérieur de foo()x。
Ici, nous allons montrer comment utiliser à la fois les variables globales et locales dans le même code.
x = "global" def foo(): global x y = "local" x = x * 2 print(x) print(y) foo()
When we run the code, the output will be:
global global local
Dans le code ci-dessus, nous déclarons x comme variable globale et y comme variable locale dans la fonction foo(). Ensuite, nous utilisons l'opérateur de multiplication*Modifier la variable globale x et afficher x et y en même temps.
After calling foo(), the value of x becomes global global because we use x * 2Print global twice. Then, we print the value of the local variable y, that is, the local variable.
x = 5 def foo(): x = 10 print("local x:", x) foo() print("global x:", x)
When we run the code, the output will be:
local x: 10 global x: 5
In the code above, we used the same name x for both global and local variables. When we print the same variable, we get different results because the variable is declared in two scopes, namely the local scope inside foo() and the global scope outside of foo().
When we print a variable inside foo(), it outputs local x: 10. This is called the local scope of the variable.
Similarly, when we print a variable outside of foo(), it will output global x: 5. This is called the global scope of the variable.
Nonlocal variables are used for nested functions that have undefined local scope. This means that the variable cannot be in the local scope nor in the global scope.
Let's see an example of how to create a global variable in Python.
We use the nonlocal keyword to create a nonlocal variable.
def outer(): x = "local" def inner(): nonlocal x x = "nonlocal" print("inner:", x) inner() print("outer:", x) outer()
When we run the code, the output will be:
inner: nonlocal outer: nonlocal
In the code above, there is a nested function inner(). We use the nonlocal keyword to create a nonlocal variable. The inner() function is defined within the scope of another function external().
NoteIf we change the value of a nonlocal variable, these changes will appear in the local variable.