getattr() 函数用于返回一个对象属性值。
def getattr(object, name, default=None): # known special case of getattr
"""
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
"""
pass
getattr()语法结构:
getattr(object, name[, default])
- object -- 对象。
- name -- 字符串,对象属性。
- default -- 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。
返回值:返回对象属性值。
示例代码1:
class Test(object):
x = 1
a = Test()
print(getattr(a, 'x')) # 获取属性 x 值
print(getattr(a, 'y', 'None')) # 获取属性 y 值不存在,但设置了默认值
# print(getattr(a, 'y')) # AttributeError: 'Test' object has no attribute 'y'
print(a.x) # 效果等同于上面
运行结果:
示例代码2:
class Demo(object):
def __init__(self):
self.name = '张三'
self.age = '25'
def first(self):
print("这是 first 方法")
return "one"
def second(self):
print("这是 second 方法")
a = Demo()
# 如果a对象中有属性name则打印self.name的值,否则打印'non-existent'
print(getattr(a, 'name', 'non-existent'))
print("*" * 100)
# 如果a对象中有属性age则打印self.age的值,否则打印'non-existent'
print(getattr(a, 'age', 'non-existent'))
print("*" * 100)
# 如果有方法first,打印其地址,否则打印default
print(getattr(a, 'first', 'default'))
print("*" * 100)
# 如果有方法first,运行函数并打印返回值,否则,打印default
print(getattr(a, 'first', 'default')())
print("*" * 100)
# 如果有方法second,运行函数并打印None否则打印default
print(getattr(a, 'second', 'default')())
运行结果: