多文件编程的目的是为了将功能上独立的源代码在物理上也独立起来(封装),已达到更高效的代码复用效果。事实上这种“封装-复用”是具有层次的,
.py
文件称为一个模块,因此多文件编程也叫做模块化编程。利用模块,可以更灵活、更安全、高效的管理和使用代码。《4 类》中下面一段代码可以创建一个办公室基本信息,可以将其写入一个文件Group.py
。
class Person:
def __init__(self,name):
self.__name = name
def getName(self) :
print(self.__name)
class Group:
def __init__(self,chargeman="None",name="None",location="None") :
self.chargeman = Person(chargeman)
self.name = name
self.location = location
def show(self) :
self.chargeman.getName()
print(self.name, self.location)
mygroup = Group("GD Liu","multiflow lab","J646")
mygroup.show()
GD Liu
multiflow lab J646
要使用这个模块,首先需要使用import
关键字导入该模块,并且该模块中的功能都必须加上模块名的前缀,相当于命名空间。
import Group as gp # 使用 as 可以避免过长的前缀
mygroup = gp.Group("GD Liu","multiflow lab","J646")
mygroup.show()
GD Liu
multiflow lab J646
若一个目标模块中含有大量的函数、类,而要是有的功能只涉及到其中一小部分,可以使用from 模块名 import 函数名
模块的__name__
属性类似编译模式对应的属性,利用其可以实现在不同的调用下,实现不同的功能。其基本原理是若文件是独立运行的,则有__name__ = __main__
,否则__name__ = 模块名
,通过这一点就可以利用分支语句来实现不同的操作。
但是本着一个模块干一件事,分支语句对应的操作应是相关的,例如模块直接运行的操作是求和并显示,模块间接运行是传递求和结果。
为了快速、低资源消耗的找到所需的模块,需要给解释器(环境)设置搜索路径。
sys
模块的功能。import sys
sys.path
['/home/wuyao/Documents/python',
'/home/wuyao/anaconda3/lib/python37.zip',
'/home/wuyao/anaconda3/lib/python3.7',
'/home/wuyao/anaconda3/lib/python3.7/lib-dynload',
'',
'/home/wuyao/anaconda3/lib/python3.7/site-packages',
'/home/wuyao/anaconda3/lib/python3.7/site-packages/IPython/extensions',
'/home/wuyao/.ipython']
假设要导入的模块在这些路径下,就可以成功导入,否则会报错。
import notexist
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
in
----> 1 import notexist
ModuleNotFoundError: No module named 'notexist'
sys.path.append(pathName)
sys.path.append("..") # 添加上层目录,一次性的,彻底修改需要在配置文件中
sys.path
['/home/wuyao/Documents/python',
'/home/wuyao/anaconda3/lib/python37.zip',
'/home/wuyao/anaconda3/lib/python3.7',
'/home/wuyao/anaconda3/lib/python3.7/lib-dynload',
'',
'/home/wuyao/anaconda3/lib/python3.7/site-packages',
'/home/wuyao/anaconda3/lib/python3.7/site-packages/IPython/extensions',
'/home/wuyao/.ipython',
'..']
一个大型项目中,可能含有多个模块,这时使用“文件”的上层“文件夹”来组织源代码,并把这个结构称为包,文件夹名字就是包的名字。
报的结构为
__init__.py
的文件,可为空(在python3中可有可无)模块名
改为包名.模块名
即可。pip
,也可以借助Anaconda
中的conda
工具来实现(见独立学习记录)。
conda list #查看当前环境下所有包
conda list -n your_env_name #查看一个非当前活跃环境下的所有包
conda install -n env_name package_name # 为指定环境安装指定包
conda remove package_name #移除当前环境下指定包
conda update package_name # 更新包
+ pip的语法是
pip list # 查看已安装的包
pip install packagesName # 安装指定包
pip show packagesName # 若已安装,返回包的位置,版本等信息
pip uninstall packagesName # 卸载指定包
pip -m pip install --upgrade pip # 升级pip
下载后,将下载得到的包文件夹放置到解释器搜索的路径下就可以使用了。
2.快速了解一个包的使用说明。
+ 首先了解其提供哪些内置方法,dir()函数
import matplotlib as plt
print(dir(plt))
['LooseVersion', 'MatplotlibDeprecationWarning', 'MutableMapping', 'Parameter', 'Path', 'RcParams', 'URL_REGEX', '_DATA_DOC_APPENDIX', '_DATA_DOC_TITLE', '_ExecInfo', '__bibtex__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', '_add_data_doc', '_all_deprecated', '_check_versions', '_color_data', '_create_tmp_config_or_cache_dir', '_deprecated_ignore_map', '_deprecated_map', '_deprecated_remain_as_none', '_ensure_handler', '_error_details_fmt', '_get_config_or_cache_dir', '_get_data_path', '_get_executable_info', '_get_xdg_cache_dir', '_get_xdg_config_dir', '_init_tests', '_label_from_arg', '_log', '_logged_cached', '_open_file_or_url', '_preprocess_data', '_rc_params_in_file', '_replacer', '_version', 'atexit', 'cbook', 'checkdep_dvipng', 'checkdep_ghostscript', 'checkdep_inkscape', 'checkdep_pdftops', 'checkdep_ps_distiller', 'checkdep_usetex', 'colors', 'compare_versions', 'contextlib', 'cycler', 'dedent', 'defaultParams', 'default_test_modules', 'fontconfig_pattern', 'ft2font', 'functools', 'get_backend', 'get_cachedir', 'get_configdir', 'get_data_path', 'get_home', 'get_label', 'get_py2exe_datafiles', 'importlib', 'inspect', 'interactive', 'is_interactive', 'is_url', 'locale', 'logging', 'matplotlib_fname', 'mplDeprecation', 'namedtuple', 'numpy', 'os', 'pprint', 'rc', 'rcParams', 'rcParamsDefault', 'rcParamsOrig', 'rc_context', 'rc_file', 'rc_file_defaults', 'rc_params', 'rc_params_from_file', 'rcdefaults', 'rcsetup', 're', 'sanitize_sequence', 'set_loglevel', 'shutil', 'subprocess', 'sys', 'tempfile', 'test', 'tk_window_focus', 'use', 'validate_backend']
可以看到这个库具有非常多的API,大部分包都会有__doc__
接口用于简要的介绍使用方法,并且通常只需要了解包开放的API即可,即没有双下划线的。(一般的小型包不会有这么多的API)
print(plt.__doc__) # 详细查看可以使用help()函数
This is an object-oriented plotting library.
A procedural interface is provided by the companion pyplot module,
which may be imported directly, e.g.::
import matplotlib.pyplot as plt
or using ipython::
ipython
at your terminal, followed by::
In [1]: %matplotlib
In [2]: import matplotlib.pyplot as plt
at the ipython shell prompt.
For the most part, direct use of the object-oriented library is
encouraged when programming; pyplot is primarily for working
interactively. The
exceptions are the pyplot commands :func:`~matplotlib.pyplot.figure`,
:func:`~matplotlib.pyplot.subplot`,
:func:`~matplotlib.pyplot.subplots`, and
:func:`~pyplot.savefig`, which can greatly simplify scripting.
Modules include:
:mod:`matplotlib.axes`
defines the :class:`~matplotlib.axes.Axes` class. Most pyplot
commands are wrappers for :class:`~matplotlib.axes.Axes`
methods. The axes module is the highest level of OO access to
the library.
:mod:`matplotlib.figure`
defines the :class:`~matplotlib.figure.Figure` class.
:mod:`matplotlib.artist`
defines the :class:`~matplotlib.artist.Artist` base class for
all classes that draw things.
:mod:`matplotlib.lines`
defines the :class:`~matplotlib.lines.Line2D` class for
drawing lines and markers
:mod:`matplotlib.patches`
defines classes for drawing polygons
:mod:`matplotlib.text`
defines the :class:`~matplotlib.text.Text`,
:class:`~matplotlib.text.TextWithDash`, and
:class:`~matplotlib.text.Annotate` classes
:mod:`matplotlib.image`
defines the :class:`~matplotlib.image.AxesImage` and
:class:`~matplotlib.image.FigureImage` classes
:mod:`matplotlib.collections`
classes for efficient drawing of groups of lines or polygons
:mod:`matplotlib.colors`
classes for interpreting color specifications and for making
colormaps
:mod:`matplotlib.cm`
colormaps and the :class:`~matplotlib.image.ScalarMappable`
mixin class for providing color mapping functionality to other
classes
:mod:`matplotlib.ticker`
classes for calculating tick mark locations and for formatting
tick labels
:mod:`matplotlib.backends`
a subpackage with modules for various gui libraries and output
formats
The base matplotlib namespace includes:
:data:`~matplotlib.rcParams`
a global dictionary of default configuration settings. It is
initialized by code which may be overridden by a matplotlibrc
file.
:func:`~matplotlib.rc`
a function for setting groups of rcParams values
:func:`~matplotlib.use`
a function for setting the matplotlib backend. If used, this
function must be called immediately after importing matplotlib
for the first time. In particular, it must be called
**before** importing pyplot (if pyplot is imported).
matplotlib was initially written by John D. Hunter (1968-2012) and is now
developed and maintained by a host of others.
Occasionally the internal documentation (python docstrings) will refer
to MATLAB®, a registered trademark of The MathWorks, Inc.
# __file__可以查看包的位置
plt.__file__
'/home/wuyao/anaconda3/lib/python3.7/site-packages/matplotlib/__init__.py'