从Python中的模块导入特定函数的点

2024-09-29 02:18:59 发布

您现在位置:Python中文网/ 问答频道 /正文

这个标题有点不言自明。如果我导入以下内容:

 import urllib.request

urllib中的其他函数也可以在脚本中使用,比如urllib.parse, urllib.错误. 那么这和进口整个东西有何不同:

^{pr2}$

示例可能看起来很简单,但有时我有一个更大的树,其中包含多个嵌套的模块和包,如果我想:

import level1.level2.level3.level4

我应该导入level1并导入整个树吗?在


Tags: 模块函数import脚本标题示例parserequest
1条回答
网友
1楼 · 发布于 2024-09-29 02:18:59

没有区别:

$ python3.2
Python 3.2.5 (default, Mar 10 2014, 10:39:23)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import urllib
>>> import urllib.request as urllib_request
>>> urllib.request is urllib_request
True

import urllib和{}都将导入模块。在

但是,表单:from <module> import <object>将导入所述模块并将对象返回到当前的命名空间或模块中。在

示例:

^{pr2}$

注意urlopen是一个函数。但也要注意:

>>> import sys
>>> sys.modules["urllib"]
<module 'urllib' from '/usr/local/Cellar/python32/3.2.5/Frameworks/Python.framework/Versions/3.2/lib/python3.2/urllib/__init__.py'>
>>> sys.modules["urllib.request"]
<module 'urllib.request' from '/usr/local/Cellar/python32/3.2.5/Frameworks/Python.framework/Versions/3.2/lib/python3.2/urllib/request.py'>

通过导入urllib.request.urlopen还可以导入模块:urllib和{}。在

参见:https://docs.python.org/3.4/tutorial/modules.html

相关问题 更多 >