English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet article, vous apprendrez à utiliser les paquets Python pour diviser les bibliothèques de code en modules propres et efficaces. De plus, vous apprendrez également comment importer et utiliser vos propres ou des paquets tiers dans des programmes Python.
Nous ne stockons généralement pas tous les fichiers au même endroit. Nous utilisons une hiérarchie de répertoires bien organisée pour faciliter l'accès.
Les fichiers similaires sont stockés dans le même répertoire, par exemple, nous pouvons conserver toutes les chansons dans le répertoire "music". De même, Python dispose de des paquets pour les répertoires et pour les fichiersmodule.
As our application grows larger and larger, with many modules, we put similar modules in one package and different modules in different packages. This makes the project (program) easy to manage and conceptually clear.
Similarly, since directories can contain subdirectories and files, Python packages can have sub-packages and modules.
The directory must contain a file named __init__.py for Python to recognize it as a package. This file can be left empty, but we usually put the initialization code of the package into this file.
This is an example. Suppose we are developing a game, then the possible package and module organization is as shown in the figure below.
We can use the dot (.) operator to import modules from a package.
For example, if you want to import the start module in the above example, please follow the following steps to complete.
import Game.Level.start
Now, if the module contains a function named select_difficulty()functionWe must use the full name to refer to it.
Game.Level.start.select_difficulty(2)
If this construction looks too long, we can import the module without the package prefix as follows.
from Game.Level import start
Now, we can simply call the function as follows.
start.select_difficulty(2)
Another method to import only the required functions (or classes or variables) from a module in a package is as follows.
from Game.Level.start import select_difficulty
Now we can call this function directly.
select_difficulty(2)
Although it is relatively simple, it is not recommended to use this method. Use the fullnamespaceThis can avoid confusion and prevent conflicts between two identical identifier names.
When importing a package, Python checks the directory list defined in sys.path, similar tomodule search path.