- 1、背景
- 2、语法
- 3、示例
hasattr函数是python的内置函数,类似print函数一样。
hasattr函数用于判断对象是否包含对应的属性。
其中builtins.py脚本中关于hasattr函数描述如下:
def hasattr(*args, **kwargs): # real signature unknown
"""
Return whether the object has an attribute with the given name.
This is done by calling getattr(obj, name) and catching AttributeError.
"""
pass
2、语法
hasattr(object, name)
其中:
object – 对象。
name – 属性名字符串。
返回值:
如果对象有该属性返回 True,否则返回 False。
查看图像数组是否有shape属性。
# encoding: utf-8
import cv2
image=cv2.imread("./2.jpeg")
if hasattr(image,"shape"):
print("[INFO]图像的形状:{0}".format(image.shape))
运行如下:



