getattr—Python
getattr() 函数用于返回一个对象属性值
class A(object):
bar = 1
a = A()
getattr(a, 'bar') # 获取属性 bar 值
print(getattr(a, 'bar')) #1
#getattr(a, 'bar2') # 属性 bar2 不存在,触发异常
#AttributeError: 'A' object has no attribute 'bar2'
getattr(a, 'bar2', 3) # 属性 bar2 不存在,但设置了默认值
print(getattr(a, 'bar2', 3)) #3
class A(object):
def set(self, a, b):
x = a
a = b
b = x
print (a, b)
a = A()
c = getattr(a, 'set')
print(c(a='1', b='2'))
’‘’
2 1
None
‘’‘