简体   繁体   English

为什么“导入PIL; PIL.Image”不行,但是“from PIL import Image”可以吗?

[英]Why does “import PIL; PIL.Image” not work, but “from PIL import Image” does?

In a python interpreter:在 python 解释器中:

>>> import PIL
>>> PIL.Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Image'
>>> from PIL import Image
>>> PIL.Image
<module 'PIL.Image' from '/usr/lib/python2.7/site-packages/PIL/Image.pyc'>

Why do I have to make the import as "from PIL import Image"?为什么我必须将导入设为“从 PIL 导入图像”? I'm interested in both "what is the underlying working in python imports that makes this behaviour possible?"我对“python 导入中使这种行为成为可能的基础工作是什么”都感兴趣? and "Why was the PIL package designed to work like this?"和“为什么 PIL 包被设计成这样工作?”

Also, I really like to keep a clean namespace when programming.另外,我真的很喜欢在编程时保持一个干净的命名空间。 If I want to use PIL.Image in my code, should I import like this:如果我想在我的代码中使用PIL.Image ,我应该像这样导入:

>>> import PIL
>>> from PIL import Image
>>> del Image

or is there a better way?或者有更好的方法吗?

You could import PIL.Image :你可以导入PIL.Image

import PIL.Image
PIL.Image.open('my_pic.jpg')

I think that Pillow is structured this way because of the history of the package.我认为 Pillow 的结构是由于包装的历史。 The original package PIL allowed you to do import Image .原始包PIL允许您执行import Image Pillow, the fork of PIL which supports Python 3, moved Image to the PIL namespace. Pillow 是支持 Python 3 的 PIL 的分支,将Image移动到PIL命名空间。 The suggested import from PIL import Image makes it easy to switch from PIL to Pillow.建议from PIL import Image可以轻松地从 PIL 切换到 Pillow。 See the porting docs for more info.有关更多信息,请参阅移植文档

PIL.Image is a submodule of PIL and so won't be automatically imported with, PIL.ImagePIL的子模块,因此不会自动导入,

import PIL

since Python doesn't recursively import submodules.因为 Python 不会递归地导入子模块。

5.4.2. 5.4.2. Submodules in the Python Language Reference may help to understand the behaviour of importing submodules. Python 语言参考中的子模块可能有助于理解导入子模块的行为。

When a submodule is loaded using any mechanism, ... a binding is placed in the parent module's namespace to the submodule object.当使用任何机制加载子模块时,...将在父模块的命名空间中放置到子模块对象的绑定。

So although after importing and loading a submodule,所以虽然在导入和加载子模块之后,

import PIL
from PIL import Image

you are able to access it via PIL.Image , this does not mean PIL.Image is loaded when importing the PIL module.您可以通过PIL.Image访问它,这并不意味着在导入PIL模块时加载了PIL.Image


Also, I couldn't find this explicitly stated anywhere but from what I've tested, it seems to be that when you import a submodule either like:另外,除了我测试过的内容之外,我在任何地方都找不到明确说明的内容,似乎是当您导入子模块时,例如:

import package.submodule

or:或:

from package import submodule

The parent package is also loaded in the process.父包也在此过程中加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM