如何检查一个对象是否具有某些属性?例如:
>>> a = SomeClass()
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'
我如何判断是否a
有属性property
使用之前?
Try hasattr() https://docs.python.org/3/library/functions.html#hasattr:
if hasattr(a, 'property'):
a.property
See 茨韦特林德的回答 https://stackoverflow.com/a/610923/117030下面,谁提供了有关请求宽恕的好建议!一个非常Pythonic的方法!
python 中的一般做法是,如果该属性在大多数情况下可能都存在,则只需调用它并让异常传播,或者使用 try/ except 块捕获它。这可能会比hasattr
。如果该属性可能大部分时间都不存在,或者您不确定,请使用hasattr
可能会比反复陷入异常块更快。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)