[Python] 06 - Modules --> Packages

故事背景


1、阶级关系

1. Programs are composed of modules.
2. Modules contain statements.
3. Statements contain expressions.
4. Expressions create and process objects.html

Package 被用来管理 modules。python

 

2、教学大纲 

 

 

 

 

Modules


1、"Imports" 基础知识 

导入module的过程

1. Find the module’s file.
2. Compile it to byte code (if needed).  【Python解释器已经把编译的字节码放在__pycache__文件夹中,*.pyc 文件】
3. Run the module’s code to build the objects it defines.linux

  

寻址策略

1. The home directory of the program                     项目路径
2. PYTHONPATH directories (if set)                     设置路径 ----> how to configure?
3. Standard library directories                         系统路径
4. The contents of any .pth files (if present)
5. The site-packages home of third-party extensionsgit

 

PYTHONPATH

>>> import sys
>>> sys.path
['', '/usr/local/anaconda3/lib/python35.zip', '/usr/local/anaconda3/lib/python3.5', '/usr/local/anaconda3/lib/python3.5/plat-linux', '/usr/local/anaconda3/lib/python3.5/lib-dynload', '/home/unsw/.local/lib/python3.5/site-packages', '/usr/local/anaconda3/lib/python3.5/site-packages', '/usr/local/anaconda3/lib/python3.5/site-packages/Mako-1.0.7-py3.5.egg', '/usr/local/anaconda3/lib/python3.5/site-packages/Sphinx-1.5.1-py3.5.egg', '/usr/local/anaconda3/lib/python3.5/site-packages/textteaser-0.3-py3.5.egg', '/usr/local/anaconda3/lib/python3.5/site-packages/requests-1.2.3-py3.5.egg', '/usr/local/anaconda3/lib/python3.5/site-packages/sputnik-0.9.3-py3.5.egg']

 

设置加载路径

[1] 请把目录C:\Python34\PCI_Code\chapter2\加到系统路径中:
>>> import sys
>>> sys.path.append("C:\Python34\PCI_Code\chapter2")
>>> from recommendations import critics
>>> 
 
[2] 或者切换到文件所在的目录中,
C:\Python34\PCI_Code\chapter2>python
>>> from recommendations import *
>>>

 

 

2、"Imports" 的使用 

from <范围> import <功能> as <别名>

  

模块的属性查看 

>>> import numpy as np

>>> list(np.__dict__.keys())
['add_docstring', 'longlong', 'geomspace', '__all__', 'moveaxis', 'character', 'unicode', 'fromstring', 'asarray_chkfinite', 'void', 'find_common_type', 'triu_indices', '_mat', 'uint64', 'get_printoptions', 'WRAP', 'recfromcsv', '_globals', 'PackageLoader', 'FPE_UNDERFLOW', 'require', 'isneginf', 'uintc', 'fill_diagonal', 'select', 'inexact', 'issubsctype', 'trunc', 'insert', 'CLIP', 'savetxt', 'int_asbuffer', 'log1p', 'base_repr', 'stack', 'in1d', 'Infinity', 'int32', 'ERR_IGNORE', 'str_', 'iscomplex', 'diag_indices', 'sinc', 'pv', 'info', 'float64', 'fv', 'timedelta64', 'floor', 'concatenate', 'einsum_path', 'ogrid', 'NaN', '__cached__', 'tile', 'testing', 'poly1d', 'ScalarType', 'numarray', 'atleast_1d', 'i0', 'object0', 'arccosh', 'isscalar', 'polysub', 'isclose', 'PZERO', 'tan', 's_', 'clongfloat', 'bitwise_not', 'ushort', 'rint', 'prod', 'inf', 'uint0', 'inner', 'sort_complex', 'amax', 'int16', 'fastCopyAndTranspose', 'real_if_close', 'not_equal', 'lib', 'SHIFT_INVALID', 'median', 'packbits', 'max', 'longfloat', 'bytes0', 'linalg', 'dot', 'float128', 'unicode_', 'interp', 'absolute', 'result_type', 'FPE_INVALID', 'mean', 'frombuffer', 'true_divide', 'nancumprod', 'float_', 'hypot', 'typename', 'percentile', 'savez_compressed', 'put', 'recarray', 'PINF', 'square', 'real', 'unpackbits', 'str0', 'remainder', 'polyadd', 'ones', 'uint32', 'sin', 'maximum', 'matrix', 'nbytes', 'safe_eval', 'datetime_data', 'rank', 'nanargmin', 'RankWarning', 'loads', 'str', 'string_', 'subtract', 'cumprod', 'amin', 'deg2rad', 'e', 'blackman', 'arccos', 'seterr', 'unique', 'sctype2char', 'recfromtxt', 'exp2', 'FLOATING_POINT_SUPPORT', 'deprecate_with_doc', 'sinh', 'bool', 'disp', 'seterrcall', 'finfo', 'repeat', 'add_newdocs', 'equal', 'UFUNC_PYVALS_NAME', 'frompyfunc', 'pmt', 'ravel', 'roots', 'extract', 'isin', 'unwrap', 'tri', 'genfromtxt', 'ix_', 'bitwise_and', 'sctypeDict', 'any', 'complex_', 'nonzero', 'iscomplexobj', 'swapaxes', 'flexible', 'mod', 'ptp', 'nan_to_num', 'sys', 'TooHardError', 'mafromtxt', 'asfortranarray', 'byte_bounds', 'cumsum', '__version__', 'uintp', 'ERR_PRINT', 'nanstd', 'hsplit', 'einsum', 'array_split', 'fabs', 'print_function', 'add_newdoc', 'arctan', 'half', 'ERR_LOG', 'broadcast_to', 'reshape', 'ComplexWarning', 'pkgload', 'MachAr', 'copyto', 'hamming', 'float16', 'polyint', 'issubdtype', 'ascontiguousarray', 'VisibleDeprecationWarning', 'RAISE', 'unravel_index', 'logical_xor', 'complex128', 'ctypeslib', 'tril', 'complexfloating', 'complex64', 'alen', 'ceil', '__name__', 'union1d', 'reciprocal', 'greater', 'zeros_like', 'polyval', 'irr', 'rad2deg', 'busdaycalendar', 'NAN', 'c_', 'bitwise_or', 'record', 'ndfromtxt', '__git_revision__', 'ERR_DEFAULT', 'fft', 'typecodes', 'kron', 'logical_and', 'is_busday', 'show_config', 'pi', 'frexp', 'number', 'rate', 'FPE_OVERFLOW', 'sort', 'where', 'ALLOW_THREADS', 'ipmt', 'modf', 'set_numeric_ops', 'typeNA', 'bitwise_xor', 'MAY_SHARE_BOUNDS', 'NINF', 'generic', 'mask_indices', 'MAXDIMS', 'take', 'intersect1d', 'matmul', 'isnat', 'place', 'searchsorted', 'argwhere', '__builtins__', 'deprecate', 'sctypeNA', 'isrealobj', '_import_tools', 'logspace', 'alltrue', 'array_str', 'test', 'array_equal', 'asscalar', 'obj2sctype', 'nanprod', 'poly', 'empty', 'arange', '__doc__', 'arcsin', 'promote_types', 'ma', 'polyfit', 'partition', 'ubyte', 'busday_count', 'set_printoptions', 'eye', 'longdouble', 'log', 'ModuleDeprecationWarning', 'geterrobj', 'fromiter', 'ppmt', 'block', 'log10', 'conj', 'rec', 'euler_gamma', 'add_newdoc_ufunc', 'sctypes', 'compress', 'ones_like', 'broadcast', 'conjugate', 'rot90', 'logical_not', 'apply_along_axis', 'round', 'vsplit', 'cross', '__file__', 'polymul', 'roll', 'logaddexp', 'sqrt', 'trapz', 'zeros', 'little_endian', 'may_share_memory', 'single', 'abs', 'resize', 'trace', '__loader__', 'fromregex', 'mgrid', 'spacing', 'vander', 'expand_dims', 'min', 'source', 'object', 'sign', 'fromfile', 'atleast_3d', 'get_include', 'tril_indices', '__package__', 'setbufsize', 'isreal', 'shape', 'ndarray', 'nanmax', 'newaxis', 'choose', 'Inf', 'tril_indices_from', 'infty', 'lookfor', 'negative', 'warnings', 'division', 'isfortran', 'log2', 'round_', 'degrees', 'array', 'average', 'split', 'argsort', 'column_stack', 'setxor1d', 'diagflat', 'compat', '_distributor_init', 'gradient', 'multiply', 'signbit', 'polyder', 'isnan', 'arctanh', 'SHIFT_DIVIDEBYZERO', 'UFUNC_BUFSIZE_DEFAULT', 'ediff1d', 'apply_over_axes', 'nanpercentile', 'indices', 'ERR_RAISE', 'digitize', 'datetime64', '__path__', 'float', 'SHIFT_UNDERFLOW', 'minimum', 'memmap', 'npv', 'fmod', 'int8', 'kaiser', 'vdot', 'arctan2', 'typeDict', 'cfloat', 'r_', 'int0', 'bincount', 'nested_iters', 'compare_chararrays', 'uint16', 'flatiter', 'tracemalloc_domain', 'ndindex', 'heaviside', 'convolve', 'flip', 'cov', 'triu_indices_from', 'arcsinh', 'row_stack', 'flatnonzero', 'identity', 'int64', 'bool8', 'dstack', 'cosh', 'meshgrid', 'loadtxt', 'fromfunction', 'lexsort', 'oldnumeric', 'nditer', 'squeeze', 'index_exp', 'floor_divide', 'tensordot', 'absolute_import', 'argpartition', 'geterr', 'Tester', 'invert', 'count_nonzero', 'nan', 'BUFSIZE', 'positive', 'mat', 'transpose', 'intp', 'csingle', 'delete', 'rollaxis', 'MAY_SHARE_EXACT', 'setdiff1d', 'singlecomplex', 'nanvar', 'corrcoef', 'iinfo', 'ERR_CALL', 'integer', 'histogramdd', 'savez', 'clip', 'allclose', 'nanmin', 'emath', 'argmax', 'fmax', 'histogram2d', 'core', 'common_type', 'load', 'piecewise', 'vectorize', 'complex256', 'nancumsum', 'flipud', 'logical_or', 'argmin', 'ldexp', 'signedinteger', 'bmat', 'mintypecode', 'bool_', 'less_equal', 'ERR_WARN', 'char', 'correlate', 'matrixlib', 'math', 'errstate', 'less', 'bytes_', 'asmatrix', 'NZERO', 'SHIFT_OVERFLOW', 'datetime_as_string', 'get_array_wrap', 'array_repr', 'diag', 'issctype', 'isinf', 'ndim', 'ravel_multi_index', 'maximum_sctype', 'triu', 'save', 'asanyarray', 'nansum', 'ufunc', 'hanning', 'expm1', 'imag', 'diagonal', 'ulonglong', '__spec__', 'geterrcall', 'nanargmax', 'full', 'chararray', 'msort', 'trim_zeros', 'random', 'std', 'int', 'FPE_DIVIDEBYZERO', 'cos', 'nanmean', 'min_scalar_type', 'greater_equal', 'True_', 'left_shift', 'linspace', 'set_string_function', 'floating', 'fmin', 'vstack', 'issubclass_', 'fliplr', 'logaddexp2', 'busday_offset', 'right_shift', 'iterable', 'bartlett', 'nanmedian', 'hstack', 'float_power', 'atleast_2d', 'isfinite', '_NoValue', 'full_like', 'short', 'ndenumerate', 'sometrue', 'shares_memory', 'asarray', 'angle', 'product', 'object_', 'cumproduct', 'uint8', 'array2string', 'var', 'dtype', 'diag_indices_from', 'histogram', 'unsignedinteger', 'divmod', 'can_cast', 'long', 'isposinf', 'array_equiv', 'putmask', 'add', 'nper', 'sum', 'polynomial', 'int_', 'complex', 'nextafter', 'polydiv', 'binary_repr', 'clongdouble', 'exp', 'cdouble', 'pad', 'intc', 'size', 'around', 'diff', 'asfarray', 'version', 'fix', 'outer', 'empty_like', 'float32', 'cbrt', 'getbufsize', '__config__', 'append', 'all', 'longcomplex', 'AxisError', 'seterrobj', 'format_parser', 'void0', 'False_', 'double', 'broadcast_arrays', 'who', 'dsplit', 'copy', 'power', 'copysign', 'uint', 'divide', 'cast', 'byte', 'DataSource', 'tanh', 'mirr', 'bench', '__NUMPY_SETUP__', 'radians']
>>>
list(np.__dict__.keys())

 

dir()的子集 __dict__

Python 下一切皆对象,每一个对象都有多个属性(attribute),Python对属性有一套统一的管理方案。app

与dir()的区别:less

    1. dir()是一个函数,返回的是list;
    2. __dict__是一个字典,键为属性名,值为属性值;
    3. dir()用来寻找一个对象的全部属性,包括__dict__中的属性,__dict__是dir()的子集

 

设置“被导入”标记

表示:让本身能用(固然本身能用),也能让其余人导入使用(具备了函数的“被调用”的功能)。dom

Ref: http://www.javashuo.com/article/p-hlkjtwtv-de.htmlide

[1] 本身使用

#module.py
def main():
  print "we are in %s"%__name__
if __name__ == '__main__':    # 是做为主程序调用 main()

打印结果:函数

”we are in __main__

 

[2] 供他人导入使用

#anothermodle.py
from module import main
main()

打印结果:

we are in module

   

 

 

Packages


1、为什么须要 “package”

三种“导入”方式

Ref: Python中import, from...import,import...as 的区别

[1] 导入所有

import datetime
print(datetime.datetime.now())

[2] 按需导入

from datetime import datetime
print(datetime.now())

[3] 起个别名

import datetime as dt print(dt.datetime.now())

 

reload() 函数

Goto: http://www.runoob.com/python/python-func-reload.html

reload 会从新加载已加载的模块,但原来已经使用的实例仍是会使用旧的模块,而新生产的实例会使用新的模块;
reload 后仍是用原来的内存地址;
reload 不支持 from ××× import ××× 格式的模块进行从新加载。

Python 3.0

from imp import reload
reload(module)

 

加载"自定义模块"

Ref: http://www.cnitblog.com/seeyeah/archive/2009/03/15/55440.html

[1] 同级目录

`-- src
    |-- mod1.py
    `-- test1.py

使用方法:

import mod1 or
from mod1 import *;

  

[2] 子目录

`-- src
    |-- mod1.py
    |-- mod2 |   `-- mod2.py
    `-- test1.py

须要在mod2文件夹中创建空文件__init__.py文件 (也能够在该文件中自定义输出模块接口);而后使用:

from mod2.mod2 import * 
or
import mod2.mod2

 

[3] 表亲目录

`-- src
    |-- mod1.py
    |-- mod2 |   `-- mod2.py
    |-- sub |   `-- test2.py
    `-- test1.py

首先须要在mod2下创建__init__.py文件 (同(2)),src下没必要创建该文件。

import sys
sys.path.append("..")  # <----
import mod1 import mod2.mod2

 

 

上述例子其实已经说起了包的概念,有点命名空间的意思。

这也解释了package存在的必要性。

 

 

2、package 概念 

有助于解决不一样应用程序中使用的模块名称之间的命名空间冲突问题。

__init__文件的"做用"

 三个做用 

__init__.py文件 的做用有以下几点:

1. 至关于class中的 def __init__(self):函数,用来初始化模块
2. 把所在目录看成一个package处理
3. from-import 语句导入子包时须要用到它。 若是没有用到, 他们能够是空文件。

 如引入package.module下的全部模块
 from package.module import *
 这样的语句会导入哪些文件取决于操做系统的文件系统. 因此咱们在__init__.py 中加入 __all__变量.
 该变量包含执行这样的语句时应该导入的模块的名字。它由一个模块名字符串列表组成。

 

 构成 package 的要素 

__init__.py 文件用于组织包(package)。这里首先须要明确包(package)的概念。什么是包(package)?

简单来讲,包是含有 python模块 的文件夹。一个 python模块(module)为一个py文件,里面写有函数和类。包(package)是为了更好的管理模块(module),至关于多个模块的父节点。 

当文件夹下有__init__.py时,表示:当前文件夹是一个package,其下的多个module统一构成一个总体。

这些module 均可以经过同一个package引入代码中。

 

__init__文件的"设置"

Ref: python的包 - Tiffany's world 提出了三个问题。

 放在哪里? 

[问题一] 如何使一个目录变成包,如何 import

# 设计一个包:Sound,且内部包含各个子模块

Sound
/|-- Effects Sound的一个子包 | |-- __init__.py | |-- errors.py | `-- iobuffer.py |-- Filters Sound的一个子包 | |-- __init__.py | |-- dolby.py | |-- equalizer.py | |-- karaoke.py | `-- vocoder.py |-- Utils Sound的一个子包 | |-- __init__.py | |-- echo.py | |-- reverse.py | `-- surround.py `-- __init__.py 文件夹下放一个__init__.py文件, 则此文件夹为包

须要用到 Sound/Utils/echo.py,则:   

import Sound.Utils.echo

 

 什么内容? 

[问题二] __init__.py 的__all__ 变量 

变量__all__指定的是指此包被import * 的时候, 哪些模块会被import进来。

[1] 若是,空文件:

Sound/__init__.py 是一个空文件,则:

>>> from Sound import * 
>>> dir()  
['__builtins__', '__doc__', '__name__'] 

[2] 若是,加一行:

__all__ = ['Effects', 'Filters', 'Utils']

以下可见对外暴露出了更多的接口:

>>> from Sound import *  
>>> dir()  
['Effects', 'Filters', 'Utils', '__builtins__', '__doc__', '__name__'] 

在这里,有必要关注下“包”中自定义属性的理解。

 

 动态调用 

[问题三] __init__.py 的 __path__ 变量。

以前的是静态调用模块中的方法,如下介绍的是“动态的策略"。

Sound/Utils/  
 |-- Linux        目录下没有__init__.py文件, 不是包, 只是一个普通目录  
 |   `-- echo.py  "I'm Linux.echo"   |-- Windows      目录下没有__init__.py文件, 不是包, 只是一个普通目录  
 |   `-- echo.py  "I'm Windows.echo"  |-- __init__.py  
 |-- echo.py     "I'm Sound.Utils.echo"   |-- reverse.py  
 `-- surround.py 

[1] 只调用外层 echo.py,则 __init__.py 为空便可。

>>> import Sound.Utils.echo  
I
'm Sound.Utils.echo

[2] 想调用全部的echo.py,则填写 __init__.py 以下。

import sys 
import os 

print "Sound.Utils.__init__.__path__ before change:", __path__   # path显示出了 __init__文件所在的(默认)路径

dirname = __path__[0] 
if sys.platform[0:5] == 'linux': 
        __path__.insert( 0, os.path.join(dirname, 'Linux') ) 
else: 
        __path__.insert( 0, os.path.join(dirname, 'Windows') ) 
print "Sound.Utils.__init__.__path__ AFTER change:", __path__

执行结果以下:【注意,这里只执行了第一个,就不执行后面的echo了】

>>> import Sound.Utils.echo 
Sound.Utils.
__init__.__path__ before change: ['Sound/Utils'] Sound.Utils.__init__.__path__ AFTER change: ['Sound/Utils/Linux', 'Sound/Utils']
I
'm Linux.echo

 

End.

相关文章
相关标签/搜索