Python导入

2020/01/30 Python

基本概念

模块:一个.py结尾的文件是模块。

包:一个包含__init__.py文件目录的是包。

导入方法

导入模块的本质:就是把python文件解释一遍。

导入包的本质:就是执行该包下的__init__.py文件。

导入模块的方法:

  • import module_name,导入一个模块
  • import module_name,module2_name,导入多噢个模块
  • from module_name import name,导入module_name里边的name
  • from module_name import *,导入module_name模块里边的所有变量,不建议使用!

导入包的方法:

  • import 包的名字

注意:

  • from a import b:a必须是模块;b可以是模块,也可以是模块里的函数、类。
  • import a:a必须是模块。
  • from a import * :默认导入存在的所有模块、函数、类别。如果设置了__all__属性,则只导入该属性中定义的模块、函数、类别
  • 模块的循环引用的问题。 (重要)Python模块和包的详细说明
  • When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.
  • In the simplest case, init.py can just be an empty file, but it can also execute initialization code for the package or set the all variable, described later.
  • Contrarily, when using syntax like import item.subitem.subsubitem, each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item.

参考

Python 中__all__的作用

Absolute vs Relative Imports in Python

from-import-vs-import

python -m参数

python 脚本的启动模式(python -m以模块方式启动)

Python实现调用另一个路径下py文件中的函数方法总结

(重要)Python模块和包的详细说明

Python官网 Modules

Search

    Table of Contents