如何检查对象是否具有某些属性?例如:
>>> 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'
如何在使用属性属性之前确定它是否具有属性属性?
当前回答
hasattr()是正确的答案。我想补充的是,hasattr()可以很好地与assert结合使用(以避免不必要的if语句,并使代码更可读):
assert hasattr(a, 'property'), 'object lacks property'
print(a.property)
如果缺少属性,程序将退出并显示AssertionError,并打印出提供的错误消息(在这种情况下,对象缺少属性)。
如SO的另一份答复所述:
断言应该用于测试不应该发生的条件。目的是在程序状态损坏的情况下尽早崩溃。
通常情况下,如果缺少属性,那么断言是非常合适的。
其他回答
希望您希望使用hasattr(),但尽量避免使用hasattr(),请选择getattr(。getattr()比hasttr()快
使用hasattr():
if hasattr(a, 'property'):
print a.property
同样,我在这里使用getattr获取属性,如果没有属性,则返回none
property = getattr(a,"property",None)
if property:
print property
这里有一个非常直观的方法:
if 'property' in dir(a):
a.property
如果a是字典,您可以正常检查
if 'property' in a:
a.property
正如贾雷特·哈迪回答的那样,哈沙特会做这个把戏。不过,我想补充一点,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()
您可以使用hasattr内置方法检查对象是否包含属性。
对于一个实例,如果您的对象是,并且您想检查属性
>>> class a:
... stuff = "something"
...
>>> hasattr(a,'stuff')
True
>>> hasattr(a,'other_stuff')
False
方法签名本身是hasattr(object,name)->bool,这意味着如果对象具有传递给hasattr中的第二个参数的属性,则根据对象中name属性的存在,它会给出布尔值True或False。
我想你要找的是哈萨特。然而,如果您想检测python财产,我建议您这样做-
try:
getattr(someObject, 'someProperty')
except AttributeError:
print "Doesn't exist"
else
print "Exists"
这里的缺点是财产__get__代码中的属性错误也会被捕获。
否则,请执行-
if hasattr(someObject, 'someProp'):
#Access someProp/ set someProp
pass
文件:http://docs.python.org/library/functions.html警告:我推荐的原因是hasattr无法检测财产。链接:http://mail.python.org/pipermail/python-dev/2005-December/058498.html