1,包和模块
包package:本质就是一个文件夹/目录,必须带一个__init.__.py的文件
模块module:.py结尾的python文件
2,导入方法
import pandas, collections # 导入多个
import pandas as pd # 起别名
3,包pakage中__init__导入方法
guxh/
|-- __init__.py # 空白
|-- ex1.py # 含有ex1.fun()
3.1,__init__函数留空
"""__init__函数中为空"""
无法通过 import package自动获得package下的module,需手工指定module。
使用guxh包时支持如下方式:
from guxh import ex1 guxh.ex1.func()
import guxh.ex1 guxh.ex1.func()
3.2,__init__函数导入module:
from . import ex1 # 相对路径导入 from guxh import ex1 # 绝对路径导入
使用时必须带上ex1模块,通过ex1模块访问func方法
使用guxh包时支持如下方式:
import guxh guxh.ex1.ex1fun()
from guxh import ex1 ex1.ex1fun()
import guxh.ex1 guxh.ex1.ex1fun()
3.3,__init__函数导入module中的方
from .ex1 import * # 相对路径导入,导入所有方法 from .ex1 import func # 相对路径导入,指定导入func方法 from guxh.ex1 import * # 绝对路径导入,导入所有方法 from guxh.ex1 import func # 绝对路径导入,指定导入func方法
这样可以让package像module,不用带上ex1模块直接使用func,同时也支持带上ex1模块访问func。
使用guxh包时支持如下方式:
import guxh guxh.ex1fun() # guxh能直接访问到ex1fun() guxh.ex1.ex1fun() # 带上ex1也行
from guxh import ex1 ex1.ex1fun()
import guxh.ex1 guxh.ex1fun() # guxh能直接访问到ex1fun() guxh.ex1.ex1fun() # 带上ex1也行
3.4,错误的导入方法
import ex1
这种导入方式,会让找不到ex1模块,但是如果是init自己运行ex1.fun()却可以
原文:https://www.cnblogs.com/guxh/p/10240777.html