之前一直搞不清楚什么时候用 import module from path, 什么时候用 import module 。最近看到一个例子好像有点儿明白
from math import sqrt
sqrt(4)
>>> 2
from cmath import sqrt
sqrt(4)
>>> (2+0j)
import module from path 不指定环境,如果其它模块里有相同名字的函数会将前面的覆盖掉。
如果是import math ,那使用的时候就要带上math.sqrt(4)。就不会冲突了。
import math
math.sqrt(4)
>>> 2
import cmath
math.sqrt(4)
>>> 2
但是呢,如果什么都是直接import model。那使用起来都要加上前缀,很麻烦,所以在确保不会重复的时候,可以尽量用 import module from path这种形式。