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)
廣告