[英]How can I get the root/parent class of an object?
如何检查对象的根/父类? 例如
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(object,type)的某些变化,但这需要非常具体:
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')
但是我觉得我应该缺少一种更pythonic的方式,对吗?
干杯
PIL图像继承自PIL.Image.Image
,因此您可以简单地通过以下方式进行测试:
if isinstance(x, PIL.Image.Image):
pass # do stuff
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.