Python 内置函数---getattr()的使用

getattr() 是 Python 的内置函数,用于动态获取对象的属性值
基本语法|getattr(object, name[, default])|

参数介绍:

  • object:要获取属性的对象
  • name:属性名(字符串)
  • default:可选,如果属性不存在时返回的默认值

1. 基本用法

python 复制代码
class Person:
    def __init__(self): 
    self.name = "张三" 
    self.age = 25
person = Person()

# 等价于 person.name 
name = getattr(person, "name") 
print(name) # 输出:张三

# 等价于 person.age 
age = getattr(person, "age") 
print(age) # 输出:25

使用默认值(属性不存在时)

python 复制代码
# 属性存在时 
email = getattr(person, "email", "未设置邮箱") 
print(email) # 输出:未设置邮箱(因为person没有email属性) 
# 等价于: 
if hasattr(person, "email"): 
    email = person.email 
else: 
    email = "未设置邮箱"

3. 动态属性名(最常用的场景)

python 复制代码
class Config: 
    def __init__(self): 
        self.host = "localhost" 
        self.port = 8080 
config = Config() 
attributes = ["host", "port", "timeout"] 
for attr in attributes: 
    value = getattr(config, attr, "未配置") 
    print(f"{attr}: {value}") 
    
# 输出: 
# host: localhost 
# port: 8080 
# timeout: 未配置

4. 获取方法(函数属性)

python 复制代码
class Calculator: 
def add(self, a, b): 
    return a + b 
    
calc = Calculator() 
# 获取方法对象 
add_method = getattr(calc, "add") 
result = add_method(3, 5) 
print(result) # 输出:8
相关推荐
DogDaoDao1 小时前
【GitHub】 Headroom 深度解析:AI Agent 上下文压缩层的完整技术拆解
人工智能·深度学习·程序员·github·ai agent·智能体·agent skill
chengliu05081 小时前
从前端转型全栈、 Agent 开发
程序员·全栈
蝎子莱莱爱打怪6 小时前
AI时代,戒骄戒躁,静下心来,想清楚,再出发!
人工智能·程序员
SimonKing7 小时前
别再自己写脚本了!DeepSeek三秒生成,豆包直接出片
java·后端·程序员
树獭非懒1 天前
从N-gram到Transformer:大语言模型架构演进之路
程序员·llm·agent
阿里嘎多学长1 天前
2026-06-13 GitHub 热点项目精选
开发语言·程序员·github·代码托管
刻意思考1 天前
AI到底提高了多少效率
程序员
AskHarries1 天前
模型降级、重试和错误处理策略
程序员
程序员老申1 天前
外呼突然全挂了,追查 24 分钟后我发现了 etcd 最阴的一颗雷
后端·程序员
Cosolar1 天前
72小时生死时速:一文读懂引爆Fable模型禁令的越狱技术风暴
人工智能·后端·程序员