怎么在使用前判断 Python 对象是否包含某个属性或者某个方法?
class FooClass:
pass
k = FooClass()
k.someAtt = 2
k.att
输出:
Traceback (most recent call last):
File "Untitled.py", line 6, in <module>
k.att
AttributeError: FooClass instance has no attribute 'att'
方法一:通过异常捕捉来实现逻辑
class FooClass:
pass
k = FooClass()
try:
#do some thing you need
print k.att
except AttributeError as e:
#error: has not attribute
pass
方法二:调用hasattr方法
hasattr(object, name)
说明:判断对象object是否包含名为name的特性(hasattr是通过调用getattr(ojbect, name)是否抛出异常来实现的)。
参数object:对象。
参数name:特性名称。
>>> hasattr(list, 'append')
True
>>> hasattr(list, 'add')
False
方法三:使用dir方法
objlist = dir(k)
if 'att' in objlist:
#do some thing you need
print k.att
else:
#error: has not attribute
pass
另外, 这种问题可以使用google搜索下,善用google
http://stackoverflow.com/questions/3681272/can-i-get-a-reference-to-a-python-property
http://stackoverflow.com/questions/191010/how-to-get-a-complete-list-of-objects-methods-and-attributes
dir(FooClass)