若是把 python 比做手机,pip
就是手机的应用商店,模块就是 手机里的 App 。python
在Python中,总共有如下四种形式的模块:函数
xxx.py
文件pip
安装的模块(应用商店下载的 App )\_\_init\_\_.py
文件,该文件夹称之为包)import 模块名
import time # 导入 time 模块 time.sleep(1) # 延时 1s
import 模块名
首次导入过程当中发生的三件事:code
time.py
中的全部代码读入名称空间,而后运行time.方法名
使用time模块中的方法from 模块名 import 具体的功能
from time import sleep sleep(1)
from 模块名 import 具体的功能
首次导入过程当中发生的三件事:ip
time.py
中的全部代码读入名称空间,而后运行sleep()
模块名import
须要加前缀;from...import...
不须要加前缀from...import...
容易与当前执行文件中名称空间中的名字冲突理解核心:内存
导入文件时发生的三件事:作用域
假设有两个文件 file1.py 和 file2.py :pycharm
# file1.py from file2 import y x = 'from file2' print(y)
# file2.py from file1 import x y = 'from file2' print(x)
对于以上两个文件:it
若是运行 file1,运行结果:pip
ImportError: cannot import name 'y' from 'file2'
若是运行 file2,运行结果:class
ImportError: cannot import name 'x' from 'file1'
这种问题就是因为循环导入引发的。
# file1.py x = 'from file2' from file2 import y print(y)
# file2.py y = 'from file2' from file1 import x print(x)
对于以上两个文件:
若是运行 file1,运行结果:
from file2 from file1 from file2
若是运行 file2,运行结果:
from file1 from file2 from file1
虽然解决了错误,可是获得了三个结果,显然不是咱们想要的内容。
利用函数定义阶段只识别语法,不执行代码的特性,将代码写进函数里面
def file1(): from file2 import y print(y) x = 'from file1' # file1()
def file2(): from file1 import x print(x) y = 'from file2' # file2()
对于以上两个文件:
若是运行 file1(须要调用f1)运行结果:
from file2
若是运行 file2(须要调用f2)运行结果:
from file1
这种方法能够解决循环导入的问题,且达到了预期的输出。
最好的解决方法是不要出现循环导入。
导入模块时查找模块的顺序是:
sys.path
中找print(sys.path)
打印结果:
# # 导入模块的时候,解释器会按照列表的顺序搜索,直到找到第一个模块 ['(当前执行文件本身保存的位置)相对路径下的当前目录', '当前执行文件的根目录', 'D:\\Program Files\\JetBrains\\PyCharm 2019.2.2\\helpers\\pycharm_display', 'D:\\Program Files\\Python\\Python37\\python37.zip', 'D:\\Program Files\\Python\\Python37\\DLLs', 'D:\\Program Files\\Python\\Python37\\lib', 'D:\\Program Files\\Python\\Python37', 'D:\\Program Files\\Python\\Python37\\lib\\site-packages', 'D:\\Program Files\\JetBrains\\PyCharm 2019.2.2\\helpers\\pycharm_matplotlib_backend']
当前正在运行的文件
当 file1 导入 file2 ,运行file1 时,file2 就是模块文件
当 file2 导入 file1 ,运行file2 时,file1 就是模块文件
__name__
__name__
是每一个文件独有的,当该文件做为执行文件运行时, __name__
等于'main';当该文件做为模块文件导入时, __name__
等于文件名。