阶级关系
1. Programs are composed of modules.
2. Modules contain statements.
3. Statements contain expressions.
4. Expressions create and process objects.
Package 用来管理 modules。
教学大纲
Modules 模块
基础概念
一、导入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.
二、寻址策略
按照如下方式查找导入模块:
1. The home directory of the program # 项目路径
2. PYTHONPATH directories (if set) # 设置路径
3. Standard library directories # 系统路径
4. The contents of any .pth files (if present)
5. The site-packages home of third-party extensions
查看 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']
设置 PYTHONPATH
(1) 请把目录 C:\Python34\PCI_Code\chapter2\ 加到系统路径中:
>>> import sys >>> sys.path.append("C:\Python34\PCI_Code\chapter2") >>> from recommendations import critics >>>
(2) 或者直接cd到文件所在的目录中,
C:\Python34\PCI_Code\chapter2>python >>> from recommendations import * >>>
"Imports" 使用法则
from <范围> import <功能> as <别名>
导入所有,还是导入一部分?
一、“模块” 的属性查看
例如,尝试查看下np的属性。
>>> 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'] >>>