[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.

相關文章
相關標籤/搜索