方法一:透過異常捕捉來實現邏輯
class FooClass: pass k = FooClass() try: #do some thing you need print k.att except AttributeError as e: #error: has not attribute pass
hasattr(object, name)說明:判斷物件object是否包含名為name的特性(hasattr是透過呼叫getattr(ojbect, name)是否丟擲異常來實現的)。 引數object:物件。 引數name:特性名稱。
>>> hasattr(list, "append")
True
>>> hasattr(list, "add")
False
objlist = dir(k)
if "att" in objlist:
#do some thing you need
print k.att
else:
#error: has not attribute
pass
百度搜索圈T社群(www.aiquanti.com) 免費影片教程
方法一:透過異常捕捉來實現邏輯
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
學習資源百度搜索圈T社群(www.aiquanti.com) 免費影片教程