python setattr/getattr

对照字典的get/update用于获取/更新键值:

test_dic = {"Lisa": 18, "Tom": 17, "Lus": 16}
k1 = test_dic.get("Lisa")
print(k1)
test_dic.update({"Lisa": 16, "Pite": 19})
print(test_dic)

# 18
# {'Lisa': 16, 'Tom': 17, 'Lus': 16, 'Pite': 19}

setattr/getattr用于获取/更新对象的属性值

def setattr(x, y, v): # real signature unknown; restored from __doc__
    """
    Sets the named attribute on the given object to the specified value.
    
    setattr(x, 'y', v) is equivalent to ``x.y = v''
    """
    pass

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

delattr用于删除对象属性

def delattr(x, y): # real signature unknown; restored from __doc__
    """
    Deletes the named attribute from the given object.
    
    delattr(x, 'y') is equivalent to ``del x.y''
    """
    pass

class Test(object):
    def __init__(self):
        self.A = 10
        self.B = 20

    def test1(self):
        pass

    def test2(self):
        pass


if __name__ == '__main__':
    tes = Test()
    print(getattr(tes, "A", 0))
    print(getattr(tes, "C", 0))
    # print(getattr(tes, "C"))
    print(getattr(tes, "test1"))

    setattr(tes, "D", 100)
    print(getattr(tes, "D", 0))
    delattr(tes, "A")
    print(getattr(tes, "A", 0))

# 10
# 0
# <bound method Test.test1 of <__main__.Test object at 0x000001F87539D5B0>>
# 100
# 0

对比:
1.get/update用于处理dict;setattr/getattr用于处理对象
2.get获取到不存在的键返回None;getattr获取不到属性抛出异常AttributeError