hasattr()
方法有助於檢查給定的對象是否具有指定的屬性。如果屬性存在,則返回 true,否則返回 false。
**hasattr(object, name) **#Where object,name shows object name and attribute name respectively.
hasattr()
參數:
取 3 個參數。getattr()
調用hasattr()
方法,檢查是否要引發屬性錯誤。getattr()
用於獲取指定對象的屬性值。
參數 | 描述 | 必需/可選 |
---|---|---|
目標 | 要檢查其命名屬性的對象 | 需要 |
名字 | 要搜索的屬性的名稱 | 需要 |
hasattr()
返回值
返回值取決於getattr()
函數。如果它引發了屬性錯誤,則返回假。否則,返回真。
| 投入 | 返回值 |
| 對象具有給定的命名屬性 | 真實的 |
| 對象沒有給定的命名屬性 | 錯誤的 |
Python 中hasattr()
方法的示例
示例hasattr()
在 Python 中是如何工作的?
class Person:
age = 23
name = 'Adam'
pers
print('Person has age?:', hasattr(person, 'age'))
print('Person has salary?:', hasattr(person, 'salary'))
輸出:
Person has age?: True
Person has salary?: False
示例hasattr()
如何使用示例?
class Employee:
id = 0
name = ''
def __init__(self, i, n):
self.id = i
self.name = n
d = Employee(10, 'Pankaj')
if hasattr(d, 'name'):
print(getattr(d, 'name'))
輸出:
Pankaj
示例hasattr()
如何返回布爾值?
class Employee:
age = 21
name = 'Phill'
employee = Employee()
print('Employee has age?:', hasattr(employee, 'age'))
print('Employee has salary?:', hasattr(employee, 'salary'))
輸出:
Employee has age?: True
Employee has salary?: False
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/285086.html