Python模块
- 通常来说,工程中不会把所有代码放在一个文件里,会把代码拆成各个模块,分别调用
- 拆成的各个模块可以看成拆成各个py文件
搜索路径
- 同文件夹下的py文件可以直接import
def print_hello();
print "hello"
将这个保存至hello.py
- 创建run.py
import hello
hello.priont_hello()
或
from hello import print_hello
print_hello()
在run.py里import, 然后调用print_hello()
- hello.py和run.py在同一目录下,可以直接import
- 如果在不同的路径下,可以在sys.path里手动添加import路径
import sys
sys.path.append('org/oxford')
import hello
hello.print_hello()
包
- 通常工程不可能只有一层目录结构,并且也不会一个一个path去append到sys中
- 常用的做法是包:一个目录及其子目录组成一个包(可以看作一个库)
- 需要添加:init.py
import sys
import os
sys.path.append('org/oxford')
from o1 import b
from o1.o2 import a
if __name__=='__main__':
b.hello_b()
a.hello_a()
- 调用只要增加将o1包append到sys即可