导入方式
import 包名
import time
time.time()
import 包名,包名
import time,sys
time.time()
sys.path
from 包名 import 模块名
from time import time
time()
from 包名 import *
from time import *
time()
补充
暴露指定属性
# test.py
__all__ = ['func1']
def func1():
print('from func1')
def func2():
print('from func2')
from test import *
func1()
func2() # NameError: name 'func2' is not defined
# 只能访问到导入原文件中 __all__ 中指定的属性
导包时的查找顺序
- Python 内部会先在
sys.modules
里面查看是否包含要导入的包\模块, 如果有,就直接导入引用。
- 如果第 1 步没有找到,Python 会在
sys.path
包含的路径下继续寻找要导入的模块名。如果有,就导入,没有就报错(PyCharm 会默认把项目路径加入到 sys.path
)。
评论区