hasattr() 函式在 Python 中的作用是什麼?
Python 中的 hasattr() 方法
hasattr() 方法在物件具有指定名稱的屬性時返回 true,在物件不具有該屬性時返回 false。
語法
hasattr() 方法的語法為 -
hasattr(object, name)
getattr() 呼叫 hasattr() 來檢查是否引發 AttributeError。
hasattr() 方法需要兩個引數 -
hasattr() 方法返回 -
如果物件具有指定名稱的屬性,則返回 True
如果物件沒有指定名稱的屬性,則返回 False
示例
class Male: age = 21 name = 'x' x = Male() print('Male has age?:', hasattr(x, 'age')) print('Male has salary?:', hasattr(x, 'salary'))
輸出
輸出為
('Male has age?:', True) ('Male has salary?:', False)
廣告