Tutorial Study Image

Python hasattr()

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


hasattr(object, name)  #Where object,name shows object name and attribute name respectively.
 

hasattr() 参数

hasattr() 方法接受 3 个参数。它通过 getattr() 方法调用,以检查是否应引发 AttributeError。getattr() 用于获取指定对象属性的值。

参数 描述 必需/可选
object  要检查其命名属性的对象 必需
名称 要搜索的属性名称 必需

hasattr() 返回值

返回值取决于 getattr() 函数。如果它抛出 AttributeError,则返回 False。否则,返回 True。

输入 返回值
对象具有给定的命名属性 True
对象没有给定的命名属性 False

Python 中 hasattr() 方法的示例

示例 1: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

示例 2: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

示例 3: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