Python 脚本名称与导入的模块名称相同

Python 脚本名称与导入的模块名称相同,python,module,pythonpath,Python,Module,Pythonpath,如果您有如下脚本: import requests requests.get() 将其命名为requests.py,您将得到一个属性错误,表示requests没有属性get,因为Python引用的是脚本名称requests,而该名称没有属性get 但是,如果我有此脚本: import time time.sleep() 我把它命名为time.py,不会有任何错误。在Python2.7.11和Python3.5.3上都进行了尝试 为什么这里不适用相同的规则?因为时间是内置的,请求是一个站点包:

如果您有如下脚本:

import requests
requests.get()
将其命名为
requests.py
,您将得到一个属性错误,表示
requests
没有属性
get
,因为Python引用的是脚本名称requests,而该名称没有属性
get

但是,如果我有此脚本:

import time
time.sleep()
我把它命名为
time.py
,不会有任何错误。在Python2.7.11和Python3.5.3上都进行了尝试


为什么这里不适用相同的规则?

因为时间是内置的,请求是一个站点包:

尝试打印
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
属性以查看模块的位置:

print(time.__file__)
AttributeError: 'module' object has no attribute '__file__'
您会得到一个错误,但通过
请求
您会得到答案

print(requests.__file__)
C:\Python34\lib\site-packages\requests\__init__.py
另一个提示由
帮助(time.\uu loader\uuuuuuuuuuuuuuuuuuuuuu)
给出:

对于请求:

>>> help(requests.__loader__)
Help on SourceFileLoader in module importlib._bootstrap object:

class SourceFileLoader(FileLoader, SourceLoader)
 |  Concrete implementation of SourceLoader using the file system.
无论如何,不要将模块称为内置模块或库包。在这两种情况下,你都会遇到问题

  • 以内置名称命名:如您所见,您无法导入它
  • 以网站包命名:您不能在模块中导入/使用网站包

因为时间是内置的,请求是一个站点包:

尝试打印
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
属性以查看模块的位置:

print(time.__file__)
AttributeError: 'module' object has no attribute '__file__'
您会得到一个错误,但通过
请求
您会得到答案

print(requests.__file__)
C:\Python34\lib\site-packages\requests\__init__.py
另一个提示由
帮助(time.\uu loader\uuuuuuuuuuuuuuuuuuuuuu)
给出:

对于请求:

>>> help(requests.__loader__)
Help on SourceFileLoader in module importlib._bootstrap object:

class SourceFileLoader(FileLoader, SourceLoader)
 |  Concrete implementation of SourceLoader using the file system.
无论如何,不要将模块称为内置模块或库包。在这两种情况下,你都会遇到问题

  • 以内置名称命名:如您所见,您无法导入它
  • 以网站包命名:您不能在模块中导入/使用网站包