Basic
定义:
To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).
文件名 = 模块名 + “.py”
Within a module, the module’s name (as a string) is available as the value of the global variable name.
模块有其自己的私有符号表,可以通过 modname.itemname 的方式来访问模块的global variable.
Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, modname.itemname.
采用 from mod import * 的引入方式是不好的,它可能会覆盖自己定义的变量。
可以通过 as 来重命名导入的变量。
For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter – or, if it’s just one module you want to test interactively, use importlib.reload(), e.g. import importlib; importlib.reload(modulename).
可以通过
if __name__ == "__main__":
# code
将其添加到结尾,来实现当前文件作为脚本运行的功能。这只有在当前的文件作为main文件执行时才会起做用。
Module Search Path
When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:
- The directory containing the input script (or the current directory when no file is specified).
- PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
- The installation-dependent default.
Compiled Python files
为了加速加载,Python把编译后的模块版本放在 pycache 文件夹中,命名方式为 module.version.pyc 。
Standard Modules
sys.ps1 sys.ps2 sys.path (初始化为 PYTHONPATH)
dir()
dir(mod): 返回module中定义的全局名称。
builtins(mod):返回内部定义的函数/变量。
dir():返回最近定义的名称。
Package
init.py 使得相应文件夹被认为是包。最简单的情况下,这个文件可以是空的,但它也可以起到初始化/设置 all 变量的作用。** all ** 的应用场合是 from package import*,它定义了哪些submodule会被导入。
先加载相同名称的文件,如果没有再按照module来加载。