"from ... import ..." 有时是必需的,而普通的 "import ..." 并不总是有效吗?为什么?
Is "from ... import ..." sometimes required and plain "import ..." not always working? Why?
我一直认为,做from x import y
然后直接使用y
,或者做import x
然后使用x.y
只是样式问题,避免命名冲突.但似乎情况并非总是如此。有时 from ... import ...
似乎是 必需的 :
Python 3.7.5 (default, Nov 20 2019, 09:21:52)
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import PIL
>>> PIL.__version__
'6.1.0'
>>> im = PIL.Image.open("test.png")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'PIL' has no attribute 'Image'
>>> from PIL import Image
>>> im = Image.open("test.png")
>>>
我是不是做错了什么?
如果不是,有人可以向我解释一下这种行为背后的机制吗?谢谢!
对于子模块,无论是否使用 from
,都必须显式导入子模块。非 from
导入应该看起来像
import PIL.Image
否则,Python将不会加载子模块,只有当包本身为您导入子模块或者之前的代码已经显式导入子模块时,子模块才能访问。
我一直认为,做from x import y
然后直接使用y
,或者做import x
然后使用x.y
只是样式问题,避免命名冲突.但似乎情况并非总是如此。有时 from ... import ...
似乎是 必需的 :
Python 3.7.5 (default, Nov 20 2019, 09:21:52)
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import PIL
>>> PIL.__version__
'6.1.0'
>>> im = PIL.Image.open("test.png")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'PIL' has no attribute 'Image'
>>> from PIL import Image
>>> im = Image.open("test.png")
>>>
我是不是做错了什么?
如果不是,有人可以向我解释一下这种行为背后的机制吗?谢谢!
对于子模块,无论是否使用 from
,都必须显式导入子模块。非 from
导入应该看起来像
import PIL.Image
否则,Python将不会加载子模块,只有当包本身为您导入子模块或者之前的代码已经显式导入子模块时,子模块才能访问。