hasattr Python · 内置函数
`hasattr(对象, '属性名')` 判断对象是否有某个属性,返回布尔值。它内部调用 `getattr` 并捕获异常。
怎么用
hasattr(对象, '属性名')
小例子
class 人:
名字 = "小明"
小明 = 人()
print(hasattr(小明, '名字')) # True
print(hasattr(小明, '年龄')) # False
**运行结果**:如上。
运行结果
True
常见使用场景
- 检查对象是否支持某个操作。 - 避免属性错误。
提醒:- 如果属性存在但值为 `None`,仍返回 `True`。
官方文档:https://docs.python.org/zh-cn/3/library/functions.html#hasattr
在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Python全部词条