给定以下类(具有错误的属性),那么检查bar
属性存在的最佳可靠方式是什么?
class Foo(object):
@property
def bar(self):
raise AttributeError('unforeseen attribute error!')
既hasattr
又getattr
都失败了,只有dir
起作用:
foo = Foo()
print hasattr(foo, 'bar')
# False
try:
getattr(foo, 'bar')
print True
except AttributeError as e:
print False
# False
print 'bar' in dir(foo)
# True
我能想到的最全面的解决方案是:
def robust_hasattr(obj, attr):
return hasattr(obj, attr) or attr in dir(obj)
有更好的方法吗?
try
和except
进行恢复,或者让其传播,如果无法恢复。 - jonrsharpeAttributeError
. It is firmly trying to signal that the attribute is not there. What is your specific usecase that you must detect that this is a property?"您的属性确实会引发AttributeError
。它坚定地试图表明该属性不存在。您必须检测到这是一个属性的特定用例是什么? - Martijn Pietersdir()
可能不够。 - Martijn Pietershasattr
的问题在于它会“失败”,从而隐藏了潜在复杂父类中的任何错误(不仅仅是AttributeError
),这使得调试实际错误变得困难。 - 101