【Python】Module

2023-04-12  本文已影响0人  盐果儿

In Python, a module is a file containing Python definitions and statements and is typically used to organize related code into reusable units. The file name is the module name with the suffix ".py" added. A module can define functions, classes, and variables, and can also include runnable code.

When you import a module into your Python script or session using the "import" statement, Python searches for the module file in the directories specified by the "sys.path" variable, compile the module code if necessary, and then executes the code in the module file.

sys.modules is a Python dictionary that stores all imported modules as values, and the module names as keys. It serves as a cache of all imported modules so that when a module is imported again in the future, Python can simply look it up in the sys.modules cache rather than reloading the module again.

When a module is loaded in Python, it means that its code has been executed and its definitions and functions are now available for use in the current Python session or script. 

Why a module needs to be loaded before use:

Namespacing: Loading a module creates a new namespace for the module's definitions and functions, separate from the global namespace of your Python script or session. This helps avoid naming conflicts and allows you to use the same name for different objects in different modules.

Code execution: Loading a module executes the code in the module file, which initializes the module's definitions and functions and prepares them for use in your Python script or session. This can include importing other modules, defining functions and classes, and setting global variables.

Code reusability: By organizing related code into modules, you can reuse the same code in multiple Python scripts or sessions. Loading a module allows you to easily access and use the code defined in the module, without having to copy and paste it into your script or session.

Terminology

Dependencies: A dependency is when one module or piece of code relies on another module or piece of code in order to function correctly.

Module: module object is a data structure that represents a Python module. A module object can contain any number of attributes, including variables, functions, and classes defined in the module.

上一篇 下一篇

猜你喜欢

热点阅读