如何检查对象是否具有某些属性?例如:
>>> 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财产,我建议您这样做-
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
其他回答
我想你要找的是哈萨特。然而,如果您想检测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
我建议避免这样做:
try:
doStuff(a.property)
except AttributeError:
otherStuff()
用户@jpalecek提到了这一点:如果doStuff()内部发生AttributeError,则表示您迷路了。
也许这种方法更好:
try:
val = a.property
except AttributeError:
otherStuff()
else:
doStuff(val)
这里有一个非常直观的方法:
if 'property' in dir(a):
a.property
如果a是字典,您可以正常检查
if 'property' in a:
a.property
您可以使用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
根据pydoc,hasattr(obj,prop)只是调用getattr(obj,prop)并捕获异常。因此,用try语句包装属性访问并捕获AttributeError与预先使用hasattr()一样有效。
a = SomeClass()
try:
return a.fake_prop
except AttributeError:
return default_value