if hasattr(obj, 'attribute'):
# do somthingvs
try:
# access obj.attribute
except AttributeError, e:
# deal with AttributeError哪一种应该是首选的?为什么?
发布于 2009-05-24 05:17:15
hasattr在内部快速执行与try/except块相同的任务:它是一个非常特定的、经过优化的单任务工具,因此在适用的情况下,它应该比非常通用的替代工具更可取。
发布于 2009-05-24 06:41:27
有没有说明性能差异的长椅?
时间是你的朋友
$ python -mtimeit -s 'class C(object): a = 4
c = C()' 'hasattr(c, "nonexistent")'
1000000 loops, best of 3: 1.87 usec per loop
$ python -mtimeit -s 'class C(object): a = 4
c = C()' 'hasattr(c, "a")'
1000000 loops, best of 3: 0.446 usec per loop
$ python -mtimeit -s 'class C(object): a = 4
c = C()' 'try:
c.a
except:
pass'
1000000 loops, best of 3: 0.247 usec per loop
$ python -mtimeit -s 'class C(object): a = 4
c = C()' 'try:
c.nonexistent
except:
pass'
100000 loops, best of 3: 3.13 usec per loop
$
|positive|negative
hasattr| 0.446 | 1.87
try | 0.247 | 3.13发布于 2013-05-24 11:18:36
还有第三种,而且通常是更好的选择:
attr = getattr(obj, 'attribute', None)
if attr is not None:
print attr优势:
getattr没有坏的exception-swallowing behavior pointed out by Martin Geiser -在旧的Python中,hasattr甚至会吞下一个KeyboardInterrupt.try/finally短,而且通常比except AttributeError短。宽的AttributeErrors块可以捕获您所期望的以外的其他,这可能会导致混淆behaviour.需要注意的一件事是,如果您关心obj.attribute设置为None的情况,则需要使用不同的标记值。
https://stackoverflow.com/questions/903130
复制相似问题