如何检查对象是否具有某些属性?例如:
>>> a = SomeClass()
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'
如何在使用属性属性之前确定它是否具有属性属性?
如何检查对象是否具有某些属性?例如:
>>> a = SomeClass()
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'
如何在使用属性属性之前确定它是否具有属性属性?
当前回答
编辑:这种方法有严重的局限性。如果对象是一个可迭代的对象,它应该可以工作。请检查下面的评论。
如果您像我一样使用Python 3.6或更高版本,有一种方便的方法可以检查对象是否具有特定属性:
if 'attr1' in obj1:
print("attr1 = {}".format(obj1["attr1"]))
然而,我不确定目前哪种方法是最好的。使用hasattr()、getattr(()或in。欢迎评论。
其他回答
我建议避免这样做:
try:
doStuff(a.property)
except AttributeError:
otherStuff()
用户@jpalecek提到了这一点:如果doStuff()内部发生AttributeError,则表示您迷路了。
也许这种方法更好:
try:
val = a.property
except AttributeError:
otherStuff()
else:
doStuff(val)
这非常简单,只需使用dir(object)这将返回对象的每个可用函数和属性的列表。
您可以使用hasattr()或catch AttributeError,但如果您真的只希望属性的值具有默认值(如果不存在),最好的选择就是使用getattr(
getattr(a, 'property', 'default value')
正如贾雷特·哈迪回答的那样,哈沙特会做这个把戏。不过,我想补充一点,Python社区中的许多人建议采用“请求宽恕比请求许可更容易”(EAFP)而不是“三思而后行”(LBYL)的策略。参见以下参考文献:
EAFP vs LBYL(Re:到目前为止有点失望)EAFP与LBYL@代码如蟒蛇:惯用Python
ie:
try:
doStuff(a.property)
except AttributeError:
otherStuff()
…优先于:
if hasattr(a, 'property'):
doStuff(a.property)
else:
otherStuff()
编辑:这种方法有严重的局限性。如果对象是一个可迭代的对象,它应该可以工作。请检查下面的评论。
如果您像我一样使用Python 3.6或更高版本,有一种方便的方法可以检查对象是否具有特定属性:
if 'attr1' in obj1:
print("attr1 = {}".format(obj1["attr1"]))
然而,我不确定目前哪种方法是最好的。使用hasattr()、getattr(()或in。欢迎评论。