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