方法一:通过异常捕捉来实现逻辑
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