質問

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. 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?

役に立ちましたか?

解決

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.

The form: from <module> import <object> however will import said module and return you the object into your current namespace or module.

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. 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.

See: https://docs.python.org/3.4/tutorial/modules.html

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top