Python hasattr() 函数用法

2023-09-17 22:27:58

hasattr() 方法检查类的对象是否具有指定的属性。

语法:

hasattr(object, name)

参数:

  1. 对象:必需。要检查其属性的对象。
  2. 名称:必需。属性的名称。

返回类型:

如果对象具有指定的属性,则返回 True,否则返回 False。

下面的示例检查内置类str是否包含指定的属性。

print('str has title: ', hasattr(str, 'title'))
print('str has __len__: ', hasattr(str, '__len__'))
print('str has isupper method: ', hasattr(str, 'isupper'))
print('str has isstring method: ', hasattr(str, 'isstring'))

输出:

str has title: True
str has len: True
str has isupper method: True
str has isstring method: False

hasattr() 方法还可以与用户定义的类一起使用,如下所示。

class student:
    name = "John"
    age = "18"
    
print("student has name: ", hasattr(student,"name"))
print("student has age: ", hasattr(student,"age"))
print("student has address: ", hasattr(student,"address"))

输出:

student has name: True
student has age: True
student has address: False