gpt4 book ai didi

python - 如何确定一个对象在 Python 中是否具有属性?

转载 作者:bug小助手 更新时间:2023-10-28 01:28:18 26 4
gpt4 key购买 nike

如何确定一个对象是否具有某些属性?例如:

>>> a = SomeClass()
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'

在使用之前如何判断a是否有属性property

最佳答案

试试 hasattr() :

if hasattr(a, 'property'):
a.property

zweiterlinde's answer下面,谁提供关于请求宽恕的好建议!一个非常pythonic的方法!

python 中的一般做法是,如果该属性可能大部分时间都存在,则只需调用它并让异常传播,或者使用 try/except block 捕获它。这可能比 hasattr 更快。如果该属性可能大部分时间都不存在,或者您不确定,使用 hasattr 可能会比反复陷入异常 block 更快。

关于python - 如何确定一个对象在 Python 中是否具有属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/610883/

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