gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:59:28 25 4
gpt4 key购买 nike

我正在阅读 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()

关于python - 为什么 "they"选择引发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25910147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com