如何检查对象是否具有某些属性?例如:
>>> 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 2.6/3.0中抽象基类的引入,这种方法也变得更加强大(基本上,ABC允许更复杂的鸭子类型)。
一种有用的情况是,如果两个不同的对象具有相同名称但含义不同的属性。仅使用hasattr可能会导致奇怪的错误。
一个很好的例子是迭代器和可迭代器之间的区别(参见这个问题)。迭代器和可迭代器中的__iter_方法具有相同的名称,但在语义上完全不同!因此,hasattr是无用的,但它与ABC一起提供了一个干净的解决方案。
然而,我同意在大多数情况下,hasattr方法(在其他答案中描述)是最合适的解决方案。
其他回答
正如贾雷特·哈迪回答的那样,哈沙特会做这个把戏。不过,我想补充一点,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()是正确的答案。我想补充的是,hasattr()可以很好地与assert结合使用(以避免不必要的if语句,并使代码更可读):
assert hasattr(a, 'property'), 'object lacks property'
print(a.property)
如果缺少属性,程序将退出并显示AssertionError,并打印出提供的错误消息(在这种情况下,对象缺少属性)。
如SO的另一份答复所述:
断言应该用于测试不应该发生的条件。目的是在程序状态损坏的情况下尽早崩溃。
通常情况下,如果缺少属性,那么断言是非常合适的。
您可以使用hasattr()检查Python中的对象或类是否具有属性。
例如,Person类如下所示:
class Person:
greeting = "Hello"
def __init__(self, name, age):
self.name = name
self.age = age
def test(self):
print("Test")
然后,可以对对象使用hasattr(),如下所示:
obj = Person("John", 27)
obj.gender = "Male"
print("greeting:", hasattr(obj, 'greeting'))
print("name:", hasattr(obj, 'name'))
print("age:", hasattr(obj, 'age'))
print("gender:", hasattr(obj, 'gender'))
print("test:", hasattr(obj, 'test'))
print("__init__:", hasattr(obj, '__init__'))
print("__str__:", hasattr(obj, '__str__'))
print("__module__:", hasattr(obj, '__module__'))
输出:
greeting: True
name: True
age: True
gender: True
test: True
__init__: True
__str__: True
__module__: True
而且,您还可以直接使用hasattr()作为类名,如下所示:
print("greeting:", hasattr(Person, 'greeting'))
print("name:", hasattr(Person, 'name'))
print("age:", hasattr(Person, 'age'))
print("gender:", hasattr(Person, 'gender'))
print("test:", hasattr(Person, 'test'))
print("__init__:", hasattr(Person, '__init__'))
print("__str__:", hasattr(Person, '__str__'))
print("__module__:", hasattr(Person, '__module__'))
输出:
greeting: True
name: False
age: False
gender: False
test: True
__init__: True
__str__: True
__module__: True
编辑:这种方法有严重的局限性。如果对象是一个可迭代的对象,它应该可以工作。请检查下面的评论。
如果您像我一样使用Python 3.6或更高版本,有一种方便的方法可以检查对象是否具有特定属性:
if 'attr1' in obj1:
print("attr1 = {}".format(obj1["attr1"]))
然而,我不确定目前哪种方法是最好的。使用hasattr()、getattr(()或in。欢迎评论。
尝试hasattr():
if hasattr(a, 'property'):
a.property
请看下面zweiterlinde的回答,他提供了关于请求宽恕的好建议!一个非常蟒蛇的方法!
python中的一般做法是,如果属性大部分时间都可能存在,那么只需调用它,让异常传播,或者用try/except块捕获它。这可能比hasattr更快。如果属性可能在大多数时间都不存在,或者您不确定,那么使用hasattr可能会比重复陷入异常块更快。