hasattr()方法有助于检查给定的对象是否具有指定的属性。如果属性存在,则返回 true,否则返回 false。

 **hasattr(object, name)  **#Where object,name shows object name and attribute name respectively. 
hasattr()参数:取 3 个参数。getattr()调用hasattr()方法,检查是否要引发属性错误。getattr()用于获取指定对象的属性值。
| 参数 | 描述 | 必需/可选 | 
|---|---|---|
| 目标 | 要检查其命名属性的对象 | 需要 | 
| 名字 | 要搜索的属性的名称 | 需要 | 
hasattr()返回值返回值取决于getattr()函数。如果它引发了属性错误,则返回假。否则,返回真。
| 投入 | 返回值 | | 对象具有给定的命名属性 | 真实的 | | 对象没有给定的命名属性 | 错误的 |
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?: Falsehasattr()如何使用示例? 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')) 
输出:
Pankajhasattr()如何返回布尔值? 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