Python hasattr() 函数
hasattr() 是 Python 中用于检查对象是否具有指定属性的内置函数。
hasattr() 返回一个布尔值,表示对象是否包含指定的属性。这在处理动态属性或需要先检查属性是否存在时非常有用。
单词释义: hasattr 是 has attribute(有属性)的缩写。
基本语法与参数
语法格式
hasattr(object, name)
参数说明
- 参数 object:
- 类型: 任意对象
- 描述: 要检查的对象。
- 参数 name:
- 类型: 字符串
- 描述: 属性名称。
函数说明
- 返回值: 返回布尔值
True或False。
实例
示例 1:基础用法
实例
class Person:
def __init__(self):
self.name = "Tom"
self.age = 20
p = Person()
# 检查属性是否存在
print(hasattr(p, "name")) # 输出: True
print(hasattr(p, "age")) # 输出: True
print(hasattr(p, "gender")) # 输出: False
# 检查方法
print(hasattr(p, "name")) # 输出: True
print(hasattr(p, "walk")) # 输出: False
def __init__(self):
self.name = "Tom"
self.age = 20
p = Person()
# 检查属性是否存在
print(hasattr(p, "name")) # 输出: True
print(hasattr(p, "age")) # 输出: True
print(hasattr(p, "gender")) # 输出: False
# 检查方法
print(hasattr(p, "name")) # 输出: True
print(hasattr(p, "walk")) # 输出: False
运行结果预期:
True True False True False
代码解析:
- hasattr() 检查对象是否有指定的属性。
示例 2:与 getattr 配合
实例
# 安全获取属性
class Config:
def __init__(self):
self.debug = True
self.port = 8080
config = Config()
# 先检查再获取
if hasattr(config, "debug"):
print(f"debug: {config.debug}")
if hasattr(config, "timeout"):
print(f"timeout: {config.timeout}")
else:
print("timeout 不存在,使用默认值")
# 输出: timeout 不存在,使用默认值
# 动态检查
attrs = ["debug", "port", "host"]
for attr in attrs:
if hasattr(config, attr):
print(f"{attr}: {getattr(config, attr)}")
class Config:
def __init__(self):
self.debug = True
self.port = 8080
config = Config()
# 先检查再获取
if hasattr(config, "debug"):
print(f"debug: {config.debug}")
if hasattr(config, "timeout"):
print(f"timeout: {config.timeout}")
else:
print("timeout 不存在,使用默认值")
# 输出: timeout 不存在,使用默认值
# 动态检查
attrs = ["debug", "port", "host"]
for attr in attrs:
if hasattr(config, attr):
print(f"{attr}: {getattr(config, attr)}")
运行结果:
实际环境运行会显示检查结果。
hasattr() 常与 getattr() 配合使用。
Python3 内置函数
点我分享笔记