English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode globals() retourne sous forme de dictionnaire toutes les variables globales à la position actuelle.
Le tableau de symboles est une structure de données maintenue par le compilateur qui contient toutes les informations nécessaires au programme.
Ces derniers incluent les noms de variables, les méthodes, les classes, etc.
Il y a principalement deux types de tableaux de symboles.
Tableau de symboles local
Tableau de symboles global
Local(Local)Le tableau de symboles stocke toutes les informations liées à la portée locale du programme et peut être utilisé en Pythonlocals()accès aux méthodes.
l'espace de nom local peut être à l'intérieur d'une fonction, d'une classe, etc.
De même,Global(Global)Le tableau de symboles stocke toutes les informations liées à la portée globale du programme et est accessible en utilisant la méthode globals() en Python.
L'espace de nom global contient toutes les fonctions, et les variables non associées à aucune classe ou fonction.
Lecture recommandée : Espaces nommés et portée en Python
Le dictionnaire globals() est le dictionnaire du module courant (dans une fonction, c'est le module qui le définit, pas celui qui l'appelle).
La syntaxe de la méthode globals() est :
globals()
La méthode globals() ne prend pas de paramètres.
La méthode globals() retourne un dictionnaire de variables globales.
globals()
When running the program, the output is:
{'In': ['', 'globals()'], 'Out': {}, '_': '', '__': '', '___': '', '__builtin__': <module 'builtins' (built-in)>, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '_dh': ['',/home/repl'], '_i': '', '_i1': 'globals()', '_ih': ['', 'globals()'], '_ii': '', '_iii': '', '_oh': {}, '_sh': <module 'IPython.core.shadows' from '/usr/local/lib/python3.5/dist-packages/IPython/core/shadows.py'>, 'exit': <IPython.core.autocall.ExitAutocall at 0x7fbc60ca6c50>, 'get_ipython': <bound method InteractiveShell.get_ipython of <IPython.core.interactiveshell.InteractiveShell object at 0x7fbc6478ee48>>, 'quit': <IPython.core.autocall.ExitAutocall at 0x7fbc60ca6c50>}
The output displays all global variables and other symbols in the current program.
age = 23 globals()['age'] = 25 print('Age is:', age)
When running the program, the output is:
Age is: 25
Here, since the global symbol table also stores all global variables, that is, age in this example, the value of age can be changed using the globals() function.
Access the returned dictionary with the key variable age and modify it as25.
This will be reflected again in the global symbol table.