python中import的引用机制引起的坑

最近在撸Scikit-Learn的代码,想加载点Seaborn的数据训练模型,简单的一句seaborn.load_dataset('')都编译通不过。

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from sklearn.linear_model import LinearRegression
# 选择模型
model = LinearRegression(fit_intercept=True)
# 整理数据
iris = sns.load_dataset('iris')
rng = np.random.RandomState(42)
x = 10* rng.rand(50)
y = 2*x - 1 + rng.randn(50)
X = x[:, np.newaxis]
#拟合数据
model.fit(X,y)
#预测
xfit = np.linspace(-1,11)
Xfit = xfit[:, np.newaxis]
yfit = model.predict(Xfit)
plt.scatter(x,y)
plt.plot(xfit, yfit)
plt.show()
PS D:\sanye\pythonDEMO> python
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> import seaborn as sns
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\sanye\pythonDEMO\seaborn.py", line 5, in <module>
    iris = sns.load_dataset('iris')
AttributeError: module 'seaborn' has no attribute 'load_dataset'

慌了,一脸懵。仔细检查发现项目路径下有一个seaborn.py文件,改名一起恢复平静。汗~
这个完全是因为python导入模块的搜索路径以及优先级问题引起的。import导入模块搜索顺序:先当前路径,再环境变量路径。

上一篇:Android WebView 文明踩坑之路


下一篇:小坑记录:get_cmap参数区分大小写