Skip to main content
 首页 » 编程设计

python之为什么 "they"选择引发异常

2025年05月04日8unruledboy

我正在阅读 hasattr built-in function :

The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.)

强调我的。

我不明白检查 getattr 函数是否引发 AttributeError 的意义,因为搜索属性本身的速度要快得多(以防万一引发异常)。

当我使用标准库时,我希望它是以最好的方式编写的。在这种情况下,引发异常真的是实现 hasattr 的最佳方式吗?

请您参考如下方法:

您不能总是搜索属性;如果对象实现动态 __getattr__ hook例如,或覆盖 __getattribute__ .

验证属性是否存在的唯一可靠方法是使用getattr()。