如何检查对象的根/父类?e.g
from PIL import Image as im
x = im.open('test.png')
type(x)
Out[]: PIL.PngImagePlugin.PngImageFile
#pseudocode:
isinstance_parent(x, PIL)
Out[]: True
我有一个列表,其中包含不同类型(PNG,JPEG等)的PIL图像对象。我希望能够检查哪些是PIL图像对象,以便稍后在脚本中关闭它们(这样我就可以删除它们)。
我已经搜索了很多,但没有找到任何适合我的答案。大多数指向使用isinstance(对象,类型)的一些变化,但这需要非常具体:
isinstance(x, PIL.PngImagePlugin.PngImageFile)
Out[]: True
但图像可以是JPG、GIF、PNG等多种类型中的一种。理想情况下,我希望能够查看是否属于PIL类。
我已经想出了一些老套的方法...只需列出每个可能的图像,看看PIL如何对它们进行分类。
或者类似这样的东西:
str(type(x))
Out[80]: "<class 'PIL.PngImagePlugin.PngImageFile'>"
if str(type(x)).split()[1].startswith('\'PIL'):
print('It is an image')
但我觉得应该有更多的蟒蛇方式,我错过了,对吧?
干杯
发布于 2019-04-02 08:12:12
PIL图像继承自PIL.Image.Image
,因此您可以简单地执行以下测试:
if isinstance(x, PIL.Image.Image):
pass # do stuff
https://stackoverflow.com/questions/55464924
复制相似问题