关于from import的问题

Young_tree 2017-08-03 09:25:58
from os.path import join
print(join('C:\\windows', 'system32'))
import os
print(os.path.join('C:\\windows', 'system32'))
import os.path
print(os.path.join('C:\\windows', 'system32'))
这三种写法都没有问题

import urllib.request
urllib.request.urlopen('http://www.http://baidu.com')
这个写法也没问题
但是
import urllib
urllib.request.urlopen('http://www.http://baidu.com')
会报错
这是为什么呢
...全文
185 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
ForestDB 2017-08-03
  • 打赏
  • 举报
回复
LZ用的应该是Python3,看以下代码片段:

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> 'path' in dir(os)
True
>>> import os.path
>>> 'join' in dir(os.path)
True
>>> import urllib
>>> 'request' in dir(urllib)
False
>>> import urllib.request
>>> 'request' in dir(urllib)
True
>>> 'urlopen' in dir(urllib.request)
True
如果只是import urllib,那么其名字空间中是没有request的,所以urllib.request.urlopen会出错。 如果推测正确,os应该是个常规包,而urllib应该是个名字空间包。 Python3我不是很熟,可以自行检阅: https://docs.python.org/3.6/reference/import.html?highlight=namespace#the-import-system https://docs.python.org/3.6/reference/import.html?highlight=namespace#regular-packages https://docs.python.org/3.6/reference/import.html?highlight=namespace#namespace-packages

37,717

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧