Try hasattr()
:
(尝试hasattr()
:)
if hasattr(a, 'property'):
a.property
EDIT: See zweiterlinde's answer below, who offers good advice about asking forgiveness!
(编辑:请参阅下面的zweiterlinde的答案 ,谁提供了关于请求宽恕的好建议!)
A very pythonic approach! (一种非常pythonic的方法!)
The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block.
(python中的一般做法是,如果属性可能在大多数时间都存在,只需调用它并让异常传播,或者使用try / except块捕获它。)
This will likely be faster than hasattr
. (这可能会比hasattr
更快。)
If the property is likely to not be there most of the time, or you're not sure, using hasattr
will probably be faster than repeatedly falling into an exception block. (如果该属性很可能在大多数时间不存在,或者您不确定,使用hasattr
可能会比重复进入异常块更快。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…