[英]Point of importing an specific function from a module in Python
Well the title is a bit self explanatory. 那么标题有点自我解释。 If I import the following:
如果我导入以下内容:
import urllib.request
Other functions from urllib will be also available in the script like urllib.parse, urllib.error. 来自urllib的其他函数也可以在urllib.parse,urllib.error等脚本中使用。 So how is that different from importing the whole thing :
那么与导入整个事物有何不同:
import urllib
The examples might seem simple, but sometimes I have a bigger tree with multiple nested modules and packages and if I want to : 示例可能看起来很简单,但有时我有一个更大的树,其中包含多个嵌套模块和包,如果我想:
import level1.level2.level3.level4
Should I just import level1 and import the whole tree? 我应该只导入level1并导入整个树吗?
There is no difference: 没有区别:
$ 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
Both import urllib
and import urllib.request
will import a module . import urllib
和import urllib.request
都将导入模块 。
The form: from <module> import <object>
however will import said module and return you the object into your current namespace or module. 表单:
from <module> import <object>
但是将导入所述模块并将对象返回到当前的命名空间或模块中。
Example: 例:
$ 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.
>>> from urllib.request import urlopen
>>> urlopen
<function urlopen at 0x1015f6af0>
Note that urlopen
is a function. 请注意,
urlopen
是一个函数。 But also note: 但也请注意:
>>> 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'>
By importing urllib.request.urlopen
you also import the modules: urllib
and urllib.request
. 通过导入
urllib.request.urlopen
您还可以导入模块: urllib
和urllib.request
。
See: https://docs.python.org/3.4/tutorial/modules.html 请参阅: https : //docs.python.org/3.4/tutorial/modules.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.