Python 怎样检查属性是否存在,同时避免执行 property?
用 Python 标准库 inspect.getattr_static 检查类或实例上的属性定义,避免执行 property,并识别静态查找的范围。
在编写调试工具或审查对象接口时,我们往往仅需确认类中是否定义了特定属性。遇到 property,可以用标准库的 inspect.getattr_static() 获取属性定义,避免执行 getter。
为什么 hasattr 会执行 getter
hasattr(obj, name) 内部调用了 getattr(obj, name)。通过实例读取 property 定义的属性时,getter 就会运行。当读取过程引发 AttributeError,hasattr() 将返回 False,其余异常会继续抛出。
用独立对象标记查找失败
利用 object() 生成一个独立对象并作为 getattr_static() 的第三个参数,随后通过 is 比对返回值与该标记。静态查找若失败,函数将返回传入的标记值。即使找到的属性值是 None,也能将它与查找失败区分开。
对比两种检查的实际行为
下面的 Report.total 在 getter 中打印一行提示。静态查找获取的是类中定义的 property 对象。getter 直至最后调用 hasattr() 时才真正执行。Python 会先计算函数实参,所以 getter 的提示会先于最后一个 print() 的结果出现。
from inspect import getattr_static
class Report:
@property
def total(self):
print("执行 total 的 getter")
return 42
report = Report()
missing = object()
attr = getattr_static(report, "total", missing)
print("静态找到 total", attr is not missing)
print("返回 property 对象", isinstance(attr, property))
print("hasattr 找到 total", hasattr(report, "total"))
预期输出
静态找到 total True
返回 property 对象 True
执行 total 的 getter
hasattr 找到 total True
留意动态属性
getattr_static() 会绕过描述符调用、__getattribute__() 以及 __getattr__()。倘若属性仅由 __getattr__() 动态提供,静态查找或许无法发现它。即使查到了描述符,仍需通过实际的属性访问来判定 getter 是否能成功返回值。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









