0
点赞
收藏
分享

微信扫一扫

Python编程Day07-Python模块



Python模块


  • ​​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.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​即可


举报

相关推荐

0 条评论