读书笔记(2019年1月)
1/12 Python高级编程
PEP文档
全称为Python Enhancement Proposals(Python改进提案),PEP0里面包含着所有被提交过的PEP文件。
包、模块
Module 模块
An object that serves as an organizational unit of Python code. Modules have a namespace containing arbitrary Python objects. Modules are loaded into Python by the process of importing.
Package 包
A Python module which can contain submodules or recursively, subpackages. Technically, a package is a Python module with an
__path__
attribute.
而Package又分为两种:
-
Regular Package
这是一种传统的包结构,这种包结构一般每个目录下都含有一个
__init__.py
文件。当这个包被导入时,这个__init__.py
文件会被隐式执行,而这个文件定义的对象将会被绑定在这个命名空间下。下面用一个例子来说明:
包结构如下:
test/ __init__.py a.py test_folder/ __init__.py b.py
我们在
test/__init__.py
文件中的代码如下:# this file is in test folder # this file will be executed before importing action print("__init__.py in folder %s run!"%__name__)
test/a.py
内容如下:from test_folder.b import foo print("This is file a") foo()
test/test_folder/__init__.py
内容如下:# this file is in test_folder folder # this file will be executed before importing action print("__init__.py in folder %s run!"%__name__)
test/test_folder/b.py
内容如下:def foo(): print("inner function foo is excuted!")
接下来,我们在命令行里面输入
python -m a
运行结果如下:
> C:\Users\Administrator\Desktop\test>python -m a __init__.py in folder test_folder run! This is file a inner function foo is excuted!
这里注意,
python -m xxx
是指把库中的模块当做脚本去运行。-m mod : run library module as a script (terminates option list)
这里相当于
import
,即当做模块去启动。 -
Namespace Package
A namespace package is a composite of various portions, where each portion contributes a subpackage to the parent package. Portions may reside in different locations on the file system. Portions may also be found in zip files, on the network, or anywhere else that Python searches during import. Namespace packages may or may not correspond directly to objects on the file system; they may be virtual modules that have no concrete representation.
Portion
A set of files in a single directory (possibly stored in a zip file) that contribute to a namespace package, as defined in PEP 420.
上面是摘自Python文档的描述,大致可以理解为,Namespace Package与Regular Package的不同之处在于,Namespace Package被分为Portion,而每个Portion可以在不同的位置,他们组成一个package靠的不是
__init__.py
而是靠的__path__
属性。Namespace Package又分为3种类型:
-
naive namespace package
在Python3.2以后,这个用法成为了官方推荐的用法。
-
pkgutil-style namespace package
-
pkg_resources-style namespace package
-
绝对导入和相对导入
首先,需要明确一点,绝对导入和相对导入都是仅用于包内部的导入。
在Python3中,所有不以点字符.
开头的import
语句格式解释为绝对导入(absolute_import)。
网友评论