是“从……进口……"吗?有时需要和简单的“导入..."不总是工作?为什么? [英] Is "from ... import ..." sometimes required and plain "import ..." not always working? Why?

查看:48
本文介绍了是“从……进口……"吗?有时需要和简单的“导入..."不总是工作?为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直认为,做from x import y然后直接使用y,或者做import x然后使用xy 只是风格和避免命名冲突的问题.但似乎情况并非总是如此.有时 from ... import ... 似乎是必需的:

I always thought, doing from x import y and then directly use y, or doing import x and later use x.y was only a matter of style and avoiding naming conflicts. But it seems like this is not always the case. Sometimes from ... import ... seems to be required:

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")
>>>

我在这里做错了吗?

如果没有,有人可以向我解释这种行为背后的机制吗?谢谢!

If not, can someone please explain me the mechanics behind this behavior? Thanks!

推荐答案

对于子模块,无论是否使用 from,都必须显式导入子模块.非from 导入应该看起来像

For submodules, you have to explicitly import the submodule, whether or not you use from. The non-from import should look like

import PIL.Image

否则,Python 将不会加载子模块,并且只有当包本身为您导入子模块或某些先前的代码已显式导入子模块时,才能访问子模块.

Otherwise, Python won't load the submodule, and the submodule will only be accessible if the package itself imports the submodule for you or if some previous code has explicitly imported the submodule.

这篇关于是“从……进口……"吗?有时需要和简单的“导入..."不总是工作?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆