import 模块1, 模块2,模块...
import ... as ...
from ... import ...
from ... import ... as ...
from ... import *
import
找到模块加载初始化,在所在作用域局部的命名空间中,增加一个名称与模块建立关联。
from
加载初始化后面的模块,但是不会把模块名称,加入的当前名称空间
dir()
内建函数,没有参数时,返回当前局部作用域的名称列表。
import 模块1, 模块2,模块...
import os, re
print(dir()) # 查看当前名称空间
# 执行结果
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'os', 're']
os, re 模块,被加载到当前的名称空间。
import os.path
print(dir()) # 查看当前名称空间
# 执行结果
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'os']
当前名称空间中,只加载了os,没有加载 path 。
import pathlib.Path
print(dir()) # 查看当前名称空间
# 执行结果
ModuleNotFoundError: No module named 'pathlib.Path'; 'pathlib' is not a package
Path 不是模块,只是pathlib模块里面的类
import ... as ...
:import threading as td
print(dir()) # 查看当前名称空间
# 执行结果
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'td']
当前名称空间内只有td
,没有threading
os.path
使用pathfrom ... import ...
from random import randint, randrange
print(dir()) # 查看当前名称空间
# 执行结果
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'randint', 'randrange']
randint, randrange 加载到名称空间
from os.path import exists
print(dir()) # 查看当前名称空间
# 执行结果
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'exists']
exists 加载到当前名称空间
from ... import ... as ...
from os.path import exists as e
print(dir()) # 查看当前名称空间
# 执行结果
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'e']
e 加载到当前名称空间
os.path
,会先加载os,让后加载path,最后加载exists,但是,只有exists或者它的别名会加入当地名称空间。from ... import *
# test1.py 文件
A = 1
D = 4
_B = 2
__C = 3
# test2.py 文件
from test1 import *
print(dir())
# test2执行结果
['A', 'D', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
在test2中,只把test1 中 变量 A, D 导入了,对私有变量、保护变量都没有导入。
# test1.py 文件
__all__ = ['A', '_B']
A = 1
D = 4
_B = 2
__C = 3
# test2.py 文件
from test1 import *
print(dir())
# test2执行结果
['A', '_B', '__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
test1 中 变量 A, _B 导入了test2。
# test1.py 文件
__all__ = []
A = 1
D = 4
_B = 2
__C = 3
# test2.py 文件
from test1 import *
print(dir())
# test2执行结果
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
没有从test1中导入
from … import *
总结from ... import *
在没有__all__的限制下,只会把所有普通变量导入。from ... import *
,导入简单,但是会导入大量不使用的变量,并且还会造成名称的冲突,尤其在自定义模块,最好使用__all__。