是 Python 内置函数之一,用于检查对象是否具有指定名称的属性或方法。使用语法是:
hasattr(object, name)
- object: 需要被检查的对象。
- name: 你想要检查的属性名或方法名。注意,这个参数是以字符串形式提供的。
返回值
如果对象具有指定名称的属性或方法,则返回 True;否则返回 False。
例子:
class ExampleClass:
def __init__(self):
self.some_attribute = "I exist!"
def some_method(self):
return "I am a method."
# 创建实例
example = ExampleClass()
# 检查属性
print(hasattr(example, 'some_attribute')) # 输出: True
print(hasattr(example, 'nonexistent')) # 输出: False
# 检查方法
print(hasattr(example, 'some_method')) # 输出: True
print(hasattr(example, 'nonexistent_meth'))# 输出: False