赞
踩
模块module,指的是Python的源代码文件
包package,指的是模块组织在一起的包名同名的目录及其相关文件
语句 | 含义 |
---|---|
import模块1[,模块2,…] | 完全导入 |
import…as… | 模块别别名 |
import functools #导入模块 print(die()) # [..., 'functools'] print(functools) # <module 'functools' from ''path/to/functools.py'> print(functools.wraps) # <function wraps at 0x0000018ECFA1AF28> 1234 import os.path # 导入os.path,os加入当前名词空间 print(dir()) #[..., 'os'] print(os) # # <module 'os' from ''path/to/os.py'> print(os.path) # 完全限定名词访问path 1234 import os.path as osp # 导入os.path并赋给osp print(dir()) # [..., 'osp'] print(osp) # <mdule 'ntpath' form 'path/to/path.py'> 123 def testimport(): import os.path # 局部 print(dir()) testimport() # ['os'] print(globals().keys()) # 没有‘os’,但有'testimport' # dict_keys(['__name__', '__doc__', '__package__',\ '__loader__', '__spec__', '__annotations__', \ '__builtins__', '__file__', '__cached__', 'testimport']) 123456789 import os.stat # 不可导入 # ModuleNotFoundError: No module named 'os.stat'; 'os' is not a package 12
语句 | 含义 |
---|---|
from…import… | 含义 |
from…import…as… | 别名 |
from pathlib import Path, PosixPath # 在当前名词空间导入该模块指定的成员 print(dir()) # [..., 'Path', 'PosixPath'] 12 from pathlib import * # 在当前名词空间导入该模块所有公共成员(非下划线开头成员)或指定成员 print(dir()) # [...,'Path', 'PosixPath', 'PurePath', 'PurePosixPath', 'PureWindowsPath', 'WindowsPath'] 12 from functools import wraps as wr,partial # 别名 print(dir)) # [..., 'wr', 'partial] 12 from os.path import exists if exists('c://'): print('Found') # Found else: print('Not Found') print(dir()) # [..., 'exists'] print(exists) # <function exists at 0x000001C57FF9AD08> 123456789
4中方式获得同一个对象exists
import os
print(os.path.exists)
print(exists)
print(os.path.__dict__['exists']) # 字符串
print(getattr(os.path, 'exists')) # 字符串
# 打印结果都为
<function exists at 0x0000022CC806AD08>
12345678
from pathlib import Path # 导入类Path
print(Path, id(Path)) # <class 'pathlib.Path'> 2089961619096
import pathlib as p1 # 导入模块使用别名
print(dir()) # [..., 'Path','p1']
print(p1) # <module 'pathlib' from 'path/to/pathlib.py'>
print(p1.Path, id(p1.Path)) # <class 'pathlib.Path'> 2089961619096
1234567
可以看出,导入的名词Path和p1.Path是统一个对象
自定义模块:.py
文件就是一个模块
# t1.py文件 print('This is t1 module') class A: def showmodule(self): print(1, self.__module__, self) print(2, self.__dict__) print(3, self.__class__.__dict__) print(4, self.__class__.__name__) a = A() a.showmodule() # t2.py文件 import t1 a = t1.A() a.showmodule() # t3.py文件 from t1 import A as cls a = cls() a.showmodule() 123456789101112131415161718192021222324
使用sys.path
查看搜索顺序
import sys
# print(*sys.path, sep='\n')
for p in sys.path:
print(p)
12345
显示结果为,Python模块的路径搜索顺序
.egg
文件,由setuptools库创建的包,第三方库常用的格式。添加了元数据(版本号、依赖项等)信息的zip文件sys.path虽可以被修改,增加新的目录,但不建议修改
# t1.py文件 print('This is t1 module') class A: def showmodule(self): print(1, self.__module__, self) print(2, self.__dict__) print(3, self.__class__.__dict__) print(4, self.__class__.__name__) a = A() a.showmodule() # t2.py文件 import t1 print('local module') import t1 import t1 # t2.py文件中执行结果 This is t1 module 1 t1 <t1.A object at 0x0000022070CD9668> 2 { } 3 { '__module__': 't1', 'showmodule': <function A.showmodule at 0x0000022070CD5268>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None} 4 A local module 123456789101112131415161718192021222324252627
从执行结果来看,不会产生重复导入的现象。
所有加载的模块都会记录在sys.modules
中,sys.modules
是储存已经加载过的所有模块的的字典
打印sys.modules可以看到os、os.path都已经加载了
__name__
,每个模块都会定义一个__name__
特殊变量来储存当前模块的名词,如果不指定,则默认为源代码文件名,如果是包则有限定名。sys.modules
字典(保存已加载的模块),加载builtins(全局函数、常量)模块、__main__
模块、sys模块,以及初始化模块搜索路径sys.path$ python t1.py
) 或交互式读取的时候,会将模块的__name__
设置为__main__
,模块的顶层代码就在__main__
这个作用域中执行。顶层代码:模块中缩进最外层的代码__name__
默认就是模块名# t1.py # 判断模块是否以程序的方式运行 if __name__ == '__main__': print('in __main__') # 程序的方式运行的代码 else: print('in imported module') # 模块导入的方式运行的代码 # 执行结果 in __main__ # t2.py import t1 # 执行结果 in imported module 123456789101112131415
if __name__ == '__main__'
:用途属性 | 含义 |
---|---|
__file__ |
字符串,源文件路径 |
__cached__ |
字符串,编译后的字节码文件路径 |
__spec__ |
显示模块的规范 |
__name__ |
模块名 |
__package__ |
当模块是包,同__name__ ;否则,可以设置为顶级模块的空字符串 |
print(__file__)
print(__name__)
# 执行结果
C:/Users/mayn/PycharmProjects/mypython/new/t3.py
__main__
123456
import m
print(m)
print(type(m))
print(dir(m)) # 没有__file__
print(m.__path__)
# 执行结果
<module 'm' (namespace)>
<class 'module'>
['__doc__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
_NamespacePath(['C:\\Users\\mayn\\PycharmProjects\\mypython\\m'])
1234567891011
__file__
,但是有__path__
__init__.py
。
pycharm中,创建Directory和创建Pyhon pcakage
不同,前者是创建普通的目录,后者是创建一个带有__init__.py
文件的目录即包
m
|-- __init__.py
|-- m1.py
|-- m2
|-- __init__.py
|-- m21
|-- __init__.py
|-- m22.py
12345678
如上建立子模块和目录和文件,所有的py文件中都写入代码print(__name__)
# 注意观察已经加载的模块、当前名词空间的名词 # import m # import m.m1 # from m import m1 # from m.m2 import m21 import m.m2.m21 print('-' * 30) print(dir()) print('-' * 30) import sys # print(sys.modules.keys()) print(sorted(filter(lambda x:x.startswith('m'), sys.modules.keys()))) # 执行结果 m m.m2 m.m2.m21 ------------------------------ ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'm'] ------------------------
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。