jazz's blog

Python Module vs. Package

模块 vs. 包

  1. 一个.py文件就是一个模块,但是一个模块未必就对应一个.py文件
    1. in lib/os.py it injects “sys.modules[‘os.path’] = path” so that you’re able to do “import os.path” as though it was a submodule.
    2. sys.modules is a dict in which modules are cached. When you import a module, if it already has been imported somewhere, it gets the instance stored in sys.modules.
  2. 包就是一个文件夹下放一个 “_init_.py”
    1. The _init.py files are required to make Python treat the directories as containing packages.
    2. _init_.py can just be an empty file, but it can also execute initialization code for the package or set the _all_ variable
    3. 多级package _init_.py从顶至底依次被执行
  3. import用于导入包或模块
    1. A module’s body executes immediately the first time the module is imported in a given run of a program
    2. An import statement creates a new namespace containing all the attributes of the module

获取帮助

  1. dir(object) => 列出object的方法
  2. help(object) => 列出object的文档
    *object 可以是模块,类 或者 函数对象