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
相关推荐
码流怪侠11 小时前
GitHub 2026年7月热门项目全景盘点:Agent Skills 生态炸裂,开源世界正在重写规则
程序员·github·agent
DogDaoDao17 小时前
【GitHub】WorldMonitor:一个工程极致主义的实时全球情报仪表盘深度解析
python·程序员·架构·github·go语言·worldmonitor·实时全球情报
zguigo18 小时前
RabbitMQ 从入门到实战:三天掌握消息队列核心与应用
程序员
字节逆旅20 小时前
有哪些工作不可以交给AI
人工智能·程序员
咔咔学姐kk21 小时前
大模型学习路线图:小白也能轻松入门,附全套学习资源,建议收藏!
人工智能·学习·ai·程序员·大模型·就业·大模型学习
程序员cxuan2 天前
Loop 还没玩明白,Graph Engineering 又火了。
人工智能·后端·程序员
谢文峰2 天前
Graph Engineering 是新范式,还是 AI 圈的又一个新词?
程序员
程序员海军2 天前
一个 AI 应用开发程序员的一天,都在屏幕前忙些什么?
前端·后端·程序员
程序员cxuan2 天前
Opus 5 深夜炸场,价格还挺香。。。
人工智能·后端·程序员