[TimLinux] Python 模块
1. 概念
模块是最高级别的程序组织单元,它将程序文件和数据封装起来以便重用。实际上,模块往往对应Python文件,每一个文件都是一个模块,并且模块导入其他模块之后就可以使用导入模块定义的变量,模块和类实际上就是一个重要的命名空间。
2. 模块的导入
- import:使导入者以一个整体获取一个模块,import b可能对应的文件:b.py, b.pyc, b.pyo, 模块包b目录,b.so/b.dll, Python内置库,b.zip文件组件(导入时自动给解压缩),内存内映射(frozen的可执行文件)。
- from:允许导入者从一个模块文件中获取特定的变量名。
- imp.reload:在不中止Python程序的情况下,提供了一种重新载入模块文件代码的方法。
import和from是赋值语句:import将整个模块对象赋值给一个变量名,from将一个或多个变量名赋值给另一个模块中同名的对象,from复制的变量名会变成对共享对象的引用。
small.py:
x = 1
y = [1,2]
from small import x,y # 从small里面拷贝两个名字
x = 42 # 改变我的x值
y[0] = 42 # 这是修改了一个对象,而不是变量名
import small
print(small.x) # 仍然为值1,获取small模块中的x,不是我的x
print(small.y) # [42, 2], y[0]被修改为42了。
from module import name1, name2概念上与下面的代码一样。
import module
name1 = module.name1
name2 = module.name2
del module
3. 模块的作用
- 代码重用:模块文件中的代码是永久的,可任意多次重新载入、运行。
- 系统命名空间的划分:模块是Python总最高级别的程序组织单元。
- 实现共享服务和数据:全局对象数据统一定义,多个代码文件间实现共享。
4. import工作原理
导入(import)是运行时的运算,程序第一次导入指定文件时,执行三个步骤:
- 查找:找到模块文件。程序所在目录,PYTHONPATH, 标准链接库目录,任何.pth文件的内容(sites-packages)(这是个内容构成:sys.path列表)
- 编译:文件编译成位码(需要时):.pyc, .pyo文件
- 执行:执行模块的代码来创建所定义的对象
以上操作,只有在第一次导入文件才需要,以后的导入操作则直接读取内存中的数据,导入的模块存放在sys.modules中.
5. 模块包
$ mkdir packages/sound/{effects,filters,utils} -p
$ cd packages/
1. 存在sound/__init__.py文件
$ python
>>> from sound import * # 没有报错,此时没有__init__.py文件
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__'] # 显示的列表中没有该sound包相关的信息
$ cat > sound/__init__.py
print("in sound.__init__.py")
__all__ = ['effects','filters','utils']
$ python
>>> from sound import *
in sound.__init__.py
>>> dir()
[..., 'effects', 'filters', 'utils'] # 多出了__all__里面配置的变量
>>> dir(effects) # 注意effects没有加引号,也就是可以直接通过effects访问,effects下当前没有__init__.py文件
2. 存在sound/__init__.py, test1.py文件
$ cat > sound/test1.py
print("in sound.test1.py")
def test():
print("in sound.test1.py:test()")
$ python
>>> from sound import * # 导入所有,但是不存在test1
in sound.__init__.py
>>> test1.test()
>>> dir(test1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'test1' is not defined
原因:test1 没有加入到 __all__中
$ cat > sound/__init__.py
print("in sound.__init__.py")
__all__ = ['effects','filters','utils','test1'] # 加入test1
$ python
>>> from sound import * # 导入所有,包含test1
in sound.__init__.py
>>> test1.test()
>>> dir(test1)
$ cat > sound/__init__.py # 恢复到不含有test1
print("in sound.__init__.py")
__all__ = ['effects','filters','utils'] # 不含有test1
$ python
>>> import sound.test1 # 单独导入test1
in sound.__init__.py
in sound.test1.py
>>> dir()
[..., 'sound'] # 全局有sound
>>> dir(sound)
[..., 'test1'] # sound内有test1,但是没有effects等定义在__all__中的模块
>>> sound.test1.test() # 可以访问
in sound.test1.py:test()
$ python
>>> from sound import test1
in sound.__init__.py
in sound.test1.py
>>> dir()
[..., 'test1'] # 有test1,不需要在__all__定义,访问了sound/__init__.py文件,没有sound
>>> dir(sound) # 出错
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sound' is not defined
>>> test1.test() # 可以访问
in sound.test1.py:test()
$ python
>>> import sound # 无法访问test1
in sound.__init__.py
>>> dir()
[..., 'sound']
>>> dir(sound) # 没有test1, 没有effects(定义在__all__变量中)
>>> sound.test1.test() # 不可以访问
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sound.test1' is not defined
$ cat > sound/__init__.py
print("in sound.__init__.py")
__all__ = ['effects','filters','utils']
from . import test1
>>> import sound # 可以访问test1
in sound.__init__.py
in sound.test1.py
>>> dir()
[..., 'sound'] # 有sound
>>> dir(sound)
[..., 'test1'] # 有test,没有effects(定义在__all__变量中)
>>> sound.test1.test() # 可以访问
in sound.test1.py:test()
总结:
1. import sound:
执行sound/__init__.py,并且解析__all__变量(如果存在的元素不存在,会抛出AttributeError异常)
a) 可以访问sound.* (*必须是在__init__.py中有定义的变量,或者通过from 语句导入的模块)
from . import test1: 可以访问sound.test1
import test1: 此时或提示无法导入模块(sys.path找不到test1.py文件)
b) 不会展开__all__变量,即无法访问sound.effects(effects内是否存在__init__.py,效果一致)
2. from sound import *:
a) 执行sound/__init__.py,并且解析__all__变量(如果存在的元素不存在,会抛出AttributeError异常)
b) 展开__all__:可以访问effects.xxx
3. from sound import test1:
执行sound/__init__.py,执行sound/test1.py,不需要在sound/__init__.py文件中做任何配置,即可访问到sound.test1.py (只需要sound/__init__.py文件存在)
扩展解释:
sound/
__init__.py
test1.py (test()) # e_test1.py要访问该方法,在e_test1.py文件中需要明确import该模块
effects/
__init__.py
e_test1.py (e_test()) # 要访问test1.py提供的方法,需要明确的import test1模块
from sound import effects.e_test1:错误,语法不支持(import后不能带.)
from sound.effects import e_test1:
- 依次调用:sound/__init__.py (不展开__all__) -> sound/effects/__init__.py(不展开__all__) -> sound/effects/e_test1.py
- 然后将e_test1 = """e_test1.py中的全部Python代码"""
- 如果sound/__ini__.py内有from . import test1.py #test1.py提供的test方法,e_test1.py内还是无法访问的,需要在e_test1.py文件内单独import(但是在真实执行时,在解析sound/__init__.py文件的时候已经解析过了,不会再次解析。
[TimLinux] Python 模块的更多相关文章
- 使用C/C++写Python模块
最近看开源项目时学习了一下用C/C++写python模块,顺便把学习进行一下总结,废话少说直接开始: 环境:windows.python2.78.VS2010或MingW 1 创建VC工程 (1) 打 ...
- Python模块之configpraser
Python模块之configpraser 一. configpraser简介 用于处理特定格式的文件,其本质还是利用open来操作文件. 配置文件的格式: 使用"[]"内包含 ...
- Python模块之"prettytable"
Python模块之"prettytable" 摘要: Python通过prettytable模块可以将输出内容如表格方式整齐的输出.(对于用Python操作数据库会经常用到) 1. ...
- python 学习第五天,python模块
一,Python的模块导入 1,在写python的模块导入之前,先来讲一些Python中的概念性的问题 (1)模块:用来从逻辑上组织Python代码(变量,函数,类,逻辑:实现一个功能),本质是.py ...
- windows下安装python模块
如何在windows下安装python模块 1. 官网下载安装包,比如(pip : https://pypi.python.org/pypi/pip#downloads) pip-9.0.1.tar. ...
- 安装第三方Python模块,增加InfoPi的健壮性
这3个第三方Python模块是可选的,不安装的话InfoPi也可以运行. 但是如果安装了,会增加InfoPi的健壮性. 目录 1.cchardet 自动检测文本编码 2.lxml 用于解析 ...
- Python基础篇【第5篇】: Python模块基础(一)
模块 简介 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护. 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就 ...
- python 模块加载
python 模块加载 本文主要介绍python模块加载的过程. module的组成 所有的module都是由对象和对象之间的关系组成. type和object python中所有的东西都是对象,分为 ...
- pycharm安装python模块
这个工具真的好好,真的很喜欢,它很方便,很漂亮,各种好 pycharm安装python模块:file-setting-搜索project inte OK
随机推荐
- MySQL添加主键和外键
查看表的字段信息:desc 表名; 查看表的所有信息:show create table 表名; 添加主键约束:alter table 表名 add constraint 主键 (形如:PK_表名) ...
- (Codeforce)The number of positions
Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say ...
- Windows下mysql的下载和安装
下载: 1.下载地址:https://www.mysql.com/downloads/ 2.选择社区版:MySQL Community (GPL) Downloads » 3.MySQL Commun ...
- nyoj 412-Same binary weight (bitset ,to_ulong())
412-Same binary weight 内存限制:64MB 时间限制:0ms 特判: No 通过数:2 提交数:3 难度:3 题目描述: The binary weight of a posit ...
- Redis单节点数据同步到Redis集群
一:Redis集群环境准备 1:需要先安装好Redis集群环境并配置好集群 192.168.0.113 7001-7003 192.168.0.162 7004-7006 2:检查redis集群 [r ...
- 力扣(LeetCode)最后一个单词的长度 个人题解
给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度. 如果不存在最后一个单词,请返回 0 . 说明:一个单词是指由字母组成,但不包含任何空格的字符串. 示例: 输入: &quo ...
- 阿里云ECS服务器部署HADOOP集群(一):Hadoop完全分布式集群环境搭建
准备: 两台配置CentOS 7.3的阿里云ECS服务器: hadoop-2.7.3.tar.gz安装包: jdk-8u77-linux-x64.tar.gz安装包: hostname及IP的配置: ...
- GitHub远程库的搭建以及使用
GitHub远程库的搭建 一).配置SSH 步骤: 1).注册GitHub账号 2).本地git仓库与远程的GitHub仓库的传输要通过SSH进行加密 3).创建SSH key 1.检查在用户主目 ...
- vue-cli从2升级到3报错error 404 Not Found: @wry/context@^0.4.0
vue3出来了,想尝尝鲜. 于是按官方的方法卸载2安装3. npm uninstall vue-cli -g npm install -g @vue/cli 但是报错了 error 404 Not F ...
- JVM 问题排查和性能优化常用的 JDK 工具
JDK 提供了一系列用于监控.诊断 Java 进程的工具,它们在 JDK 安装目录的 bin 目录下,有 jps.jcmd.jstack.jinfo.jmap 等.其中jmc.jconsole.jvi ...