无论何时导入相对于当前脚本/包的包,都会发生相对导入。
以下面的树为例:
mypkg
├── base.py
└── derived.py
现在,您的derived.py需要math的内容。在Python 2中,您可以这样做(在../中):
from base import BaseThing
Python 3不再支持它,因为它不明确你是否想要'relative'或'absolute'math.换句话说,如果在系统中安装了一个名为../的Python包,你就会得到错误的包。
相反,它要求您使用显式导入,它明确指定模块在路径上的位置。 您的math看起来像是:
from .base import BaseThing
领先的math表示'从模块目录导入../'; 换句话说,..mod映射到../mod.py。
类似地,有math前缀,其上升到目录层次结构,如../(与..mod映射到../mod.py),然后...上升两个级别(../../mod.py),依此类推。
但是请注意,上面列出的相对路径是相对于当前模块(math)所在的目录,而不是当前工作目录。
@BrenBarn已经解释了明星进口案例。 为了完整,我将不得不说同样的;)。
例如,您需要使用一些math函数,但只能在单个函数中使用它们。 在Python 2中,你被允许是半懒惰的:
def sin_degrees(x):
from math import *
return sin(degrees(x))
请注意,它已在Python 2中触发警告:
a.py:1: SyntaxWarning: import * only allowed at module level
def sin_degrees(x):
在现代Python 2代码中,您应该在Python 3中执行以下任一操作:
def sin_degrees(x):
from math import sin, degrees
return sin(degrees(x))
要么:
from math import *
def sin_degrees(x):
return sin(degrees(x))