使用getattr时若属性不存在且未提供默认值会抛出AttributeError,例如print(getattr(p, "age"))报错;通过提供默认值可避免错误,如print(getattr(p, "age", None))输出None;也可用hasattr先检查属性是否存在,再安全访问。

在 Python 中使用 getattr 获取不存在的属性时,默认行为不会直接报错,而是取决于你如何调用它。如果你不提供默认值且属性不存在,getattr 会抛出 AttributeError。
getattr(object, name[, default]) 接受三个参数:
如果没有提供 default 参数且属性不存在,就会引发 AttributeError。
以下代码会出错:
立即学习“Python免费学习笔记(深入)”;
class Person:
def __init__(self):
self.name = "Alice"
<p>p = Person()
print(getattr(p, "age")) # 抛出 AttributeError: 'Person' object has no attribute 'age'</p>因为 age 属性不存在,又没有提供默认值,所以 getattr 触发异常。
安全使用 getattr 的方式是提供第三个参数作为默认值:
print(getattr(p, "age", None)) # 输出: None print(getattr(p, "age", 0)) # 输出: 0 print(getattr(p, "age", "未知")) # 输出: 未知
这样即使属性不存在,也不会报错,而是返回你指定的默认值。
你也可以用 hasattr 先判断属性是否存在:
if hasattr(p, "age"):
print(getattr(p, "age"))
else:
print("属性不存在")
这种方法适合需要做复杂处理的场景。
基本上就这些。只要记得给 getattr 提供默认值,就能避免大多数因属性不存在导致的错误。
以上就是getattr在python中获取不存在属性出错的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号