认识
将代码分成多个文件或模块,提高代码的可维护性和重用性。
组成
Module —— the basic unit of code reusability in Python: a block of code imported by some other code. Three types of modules concern us here:
pure Python modules
a module written in Python and contained in a single .py file (and possibly associated .pyc files). Sometimes referred to as a “pure module.”
简而言之,其仅包含 Python 代码。
extension modules
a module written in the low-level language of the Python implementation: C/C++ for Python, Java for Jython. Typically contained in a single dynamically loadable pre-compiled file, e.g. a shared object (.so) file for Python extensions on Unix, a DLL (given the .pyd extension) for Python extensions on Windows, or a Java class file for Jython extensions. (Note that currently, the Distutils only handles C/C++ extensions for Python.)
简而言之,该类模块包含平台相关代码。
性质
__all__ = []
- It is a list of strings defining what symbols in a module will be exported when from <module> import * is used on the module.
- __all__ affects the from <module> import * behavior only. Members that are not mentioned in __all__ are still accessible from outside the module and can be imported with from <module> import <member>.
import <module_name>
‘import’ vs ‘from import’ in Python — What’s The Difference?
import os import os as RealOs import datetime d1 = datetime.date(2021, 10, 19)
import *
the default behaviour of import * is to import all symbols that do not begin with an underscore, from the given namespace.
from <module_name> import <class/func>
PEP 221 — Import As | Python.org
python – How do I call a function from another .py file? – Stack Overflow
How to Import Class from Another File in Python | by Teamcode | Medium
from os import path as p # --------------------------------------------------------- # Import a Class from myclass import MyClass my_instance = MyClass() # --------------------------------------------------------- # Import a Function from filebar import funcbar funcbar(a, b)
构建
安装模块:Installing Python Modules
发布模块:Distributing Python Modules
应用
如何通过“绝对路径”来使用模块名
针对部分模块,我们很少使用,所以我们并不想使用 import 语句来导入模块,而是希望直接使用模块。
# python
Python 3.12.10 (main, May 1 2025, 20:33:51) [GCC 14.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a=1
>>> b=2
>>> print(__import__('operator').lt(a,b))
True
>>>