问题描述
为什么hasattr
说实例没有foo
属性?
>>> class A(object):
... @property
... def foo(self):
... ErrorErrorError
...
>>> a = A()
>>> hasattr(a, 'foo')
False
我期望:
>>> hasattr(a, 'foo')
NameError: name 'ErrorErrorError' is not defined`
hasattr 相当幼稚,它只是尝试访问该属性并查看它是否引发异常.
不幸的是,这意味着属性中任何未处理的异常都将被吞噬,并且该代码中的错误可能会丢失.为了增加侮辱性的伤害,当hasattr吞噬异常时,它还会返回错误的答案(此处属性a.foo
确实存在,因此结果应该返回True
)./p>
在python3.2 +中,行为已得到纠正:
此修复程序是此处,但很遗憾,该更改并未向后移植./p>
如果python2行为给您带来麻烦,请考虑避免使用hasattr
;相反,您可以在 getattr
周围使用try/except,仅捕获AttributeError
异常,并让其他任何异常都无法处理.
Why does hasattr
say that the instance doesn't have a foo
attribute?
>>> class A(object):
... @property
... def foo(self):
... ErrorErrorError
...
>>> a = A()
>>> hasattr(a, 'foo')
False
I expected:
>>> hasattr(a, 'foo')
NameError: name 'ErrorErrorError' is not defined`
The python2 implementation of hasattr is fairly naive, it just tries to access that attribute and see whether it raises an exception or not.
Unfortunately, this means that any unhandled exceptions inside properties will get swallowed, and errors in that code can get lost. To add insult to injury, when hasattr eats the exception, it will also return an incorrect answer (here the attribute a.foo
does exist, so the result should have returned True
if anything).
In python3.2+, the behaviour has been corrected:
The fix is here, but unfortunately that change didn't backport.
If the python2 behaviour causes trouble for you, consider to avoid using hasattr
; instead you can use a try/except around getattr
, catching only the AttributeError
exception and letting any others raise unhandled.
这篇关于Python的hasattr有时返回不正确的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!