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

Python Basic Tutorial

Python Flow Control

Fonctions en Python

Types de données en Python

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Namespace et portée en Python

In this article, you will learn about namespaces, the mapping from names to objects, and the scope of variables.

What are namespaces in Python?

If you have ever read 'The Zen of Python' (type import this in the Python interpreter), the last line points out that,Namespaces are a great idea-Let's do more things!So what are these mysterious namespaces? First, let's see what a name is.

Names (also known as identifiers) are just the names given to objects. Everything in Python isobjects. Names are a way to access the base object.

For example, when we perform an assignment operation a = 2,2is an object stored in memory, whileaare the names associated with them. We can accessBuilt-in functions Get the address of some objects (in RAM) using id(). Let's see how to use it.

# Attention: You may receive different id values
a = 2
print('id(2) = ', id(2))
print('id(a) = ', id(a))

Résultat de la sortie

id(2) = 9302208
id(a) = 9302208

Here, both refer to the same object2, so they have the same id(). Let's do something interesting.

# Attention: You may receive different id values
a = 2
print('id(a) = ', id(a))
a = a+1
print('id(a) = ', id(a))
print('id(3) = ', id(3))
b = 2
print('id(b) = ', id(b))
print('id(2) = ', id(2))

Résultat de la sortie

id(a) = 9302208
id(a) = 9302240
id(3) = 9302240
id(b) = 9302208
id(2) = 9302208

Qu'est-ce qui se passe dans cette séquence d'étapes ? Laissez-nous expliquer avec un graphique :

Graphique de la mémoire des variables en Python

Initialement, un objet est créé2sera créé un nouvel objet + 1Lorsque3) maintenant a est lié à cet objet.

Veuillez noter que id(a) et id(3) a la même valeur.

En plus, lorsque l'exécution de b = 2Lorsque b =2Liés.

C'est valable, car Python n'a pas besoin de créer un nouvel objet redondant. Cette caractéristique dynamique de liage des noms rend Python puissant. Les noms peuvent faire référence à n'importe quel type d'objet.

>>> a = 5
>>> a = 'Hello World!'
>>> a = [1,2,3]

Ce sont tous valides etaNous allons faire référence à trois types différents d'objets dans différents exemples.FonctionSont également des objets, donc les noms peuvent également les faire référence.

def printHello():
    print("Hello")
a = printHello
a()

Résultat de la sortie

Hello

Même nomaOn peut faire référence à une fonction, on peut utiliser ce nom pour appeler la fonction.

Qu'est-ce qu'un espace de noms en Python ?

Maintenant que nous avons compris ce que sont les noms, nous pouvons continuer à discuter du concept d'espace de noms.

En résumé, un espace de noms est un ensemble de noms.

En Python, vous pouvez imaginer un espace de noms comme une carte de chaque nom à l'objet correspondant.

Des espaces de noms différents peuvent coexister à un moment donné, mais sont complètement isolés.

Lorsque nous démarrons l'interpréteur Python, un espace de noms contenant tous les noms intégrés est créé, et tant que l'interpréteur s'exécute, cet espace de noms existe.

Voilà pourquoi les fonctions intégrées (comme id()) et print() peuvent toujours être utilisées à partir de n'importe quelle partie du programme. ChaqueModuleCréez votre propre espace de noms global.

Ces espaces de noms différents sont isolés. Par conséquent, les noms identiques qui pourraient exister dans différents modules ne seront pas en conflit.

Les modules peuvent avoir diverses fonctions et classes. Lorsque vous appellez une fonction, un espace de noms local est créé, où sont définies toutes les noms. Similaire à une classe. Le graphique suivant pourrait aider à clarifier ce concept.

Graphique des espaces de noms différents en Python

Portée des variables Python

Bien que des espaces de noms uniques aient été définis, nous ne pourrions peut-être pas accéder à eux à partir de chaque partie du programme. Le concept de portée commence à jouer.

Scope is a part of the program from where namespaces can be accessed directly without any prefix.

At any given moment, there are at least three nested scopes.

  1. The scope of the current function with local names

  2. The scope of the module with global names

  3. The outermost scope with built-in names

When referencing within a function, the name is searched in the local namespace, then in the global namespace, and finally in the built-in namespace.

If there is another function inside a function, the new scope is nested within the local scope.

Example of Python scope and namespace

def outer_function():
    b = 20
    def inner_func():
        c = 30
a = 10

Here, the variableain the global namespace. The variablebin the local namespace of outer_function() whilecin the nested local namespace of inner_function().

when we are in inner_function()cin our localbin the non-localain the global. We can assigncread and assign a new value, but can only be read frombandainner_function().

If we try to assign as a valueb, a new variablebThe creation of a new variable is different in the local namespace than in the non-localb. The same thing happens when we assign a valueOne.

However, if we willadeclared as global a, all references and assignments will be moved to the globalaSimilarly, if we want to rebind the variablebIf you want to rebind a variable, it must be declared as a non-local variable. The following example will further illustrate this point.

def outer_function():
    a = 20
    def inner_function():
        a = 30
        print('a =
    inner_function()
    print('a =
a = 10

print('a =

As you can see, the output of the program is

a = 30
a = 20
a = 10

In this program, three different variables are defined in different namespaces.aand the corresponding access has been performed. In the following program,

def outer_function():
    global a
    a = 20
    def inner_function():
        global a
        a = 30
        print('a =
    inner_function()
    print('a =
a = 10

print('a =

The output of the program is.

a = 30
a = 30
a = 30

Here, since the keyword global is used, all references and assignments point to the global variable a.