Python编程Day07-Python模块

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.pyimport, 然后调用print_hello()

  • hello.pyrun.py在同一目录下,可以直接import
  • 如果在不同的路径下,可以在sys.path里手动添加import路径
import sys
sys.path.append('org/oxford')
import hello
hello.print_hello()

  • 通常工程不可能只有一层目录结构,并且也不会一个一个pathappendsys
  • 常用的做法是包:一个目录及其子目录组成一个包(可以看作一个库)
  • 需要添加: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()
  • 调用只要增加将o1appendsys即可
发布了113 篇原创文章 · 获赞 95 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/JewaveOxford/article/details/103265317