当我使用PIL时,我必须导入大量的PIL模块。我尝试了三种方法来做到这一点,但最后一种方法对我来说是合乎逻辑的,尽管最后一种方法是可行的:
导入完整的PIL并在代码中调用它的模块: NOPE
>>> import PIL
>>> image = PIL.Image.new('1', (100,100), 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Image'
从PIL导入所有东西:不
>>> from PIL import *
>>> image = Image.new('1', (100,100), 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Image' is not defined
从PIL导入一些模块: OK
>>> from PIL import Image
>>> image = Image.new('1', (100,100), 0)
>>> image
<PIL.Image.Image image mode=1 size=100x100 at 0xB6C10F30>
>>> # works...
我在这里没有得到什么?
发布于 2016-06-11 23:48:15
PIL本身不导入任何子模块。这其实很常见。
因此,当您使用from PIL import Image
时,您实际上定位了Image.py
文件并导入该文件,而当您试图在import PIL
之后调用PIL.Image
时,您正在尝试对一个空模块进行属性查找(因为您没有导入任何子模块)。
同样的理由也适用于为什么from PIL import *
不能工作-您需要显式导入Image子模块。无论如何,由于将发生名称空间污染,from ... import *
被视为不好的做法--您最好的选择是使用from PIL import Image
。
此外,PIL不再被维护,但是为了向后兼容的目的,如果您使用from PIL import Image
,您可以确保您的代码将保持与仍然维护的枕头兼容(就像只使用import Image
一样)。
https://stackoverflow.com/questions/37771395
复制