擅长:python、mysql、java
<p>似乎<code>hasattr</code>有吞咽异常的问题(至少<a href="https://twitter.com/Yhg1s/status/492895232078258177" rel="nofollow">in Python 2.7</a>),所以在修复之前最好远离它。</p>
<p>例如,<a href="https://community.plone.org/t/is-hasattr-really-harmful/957/2?u=hvelarde" rel="nofollow">the following code</a>:</p>
<pre class="lang-py prettyprint-override"><code>>>> class Foo(object):
... @property
... def my_attr(self):
... raise ValueError('nope, nope, nope')
...
>>> bar = Foo()
>>> bar.my_attr
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in my_attr
ValueError: nope, nope, nope
>>> hasattr(Foo, 'my_attr')
True
>>> hasattr(bar, 'my_attr')
False
>>> getattr(bar, 'my_attr', None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in my_attr
ValueError: nope, nope, nope
>>>
</code></pre>