模块的导入。真正的用处在于他们像类一样可以保持自己的作用域。这就意味着所有的类和函数以及赋值后的变量都成为模块的特性。
#D:\hello2.py
def hello():
print "hello word"
>>>import sys
>>>sys.path.append('D:\hello2.py')
>>>import hello2
>>>>hello2.hello()
hello word
那么问题来了怎么让我的模块可用呢?
- 将模块放置在合适的位置:
找到**site—packages**目录.将你**.py**文件放进去就可以正常导入啦。
>>>import hello2
>>>hello2.hello()
hello word
- 告诉解释器去哪里查找需要的模块:
一种方法就是前面所说的sys.path.append(‘你的模块文件’)。
另一种就是标准的实现方法:在PYTHONPATH环境变量中包含模块所在目录。各种操作系统设置环境变量。
包
包含_init_.py与其他程序文件的文件夹。_init_.py标志此文件夹是一个包。drawing/init.py 中包含 shapes.py和colors.py文件。
import drawing
import drawing.shapes #通过drawing.shapes来使用
from drawing import colors #可以直接通过colors来使用