首先我们回顾下字典的update方法,以及查看对象属性__dict__的使用;然后再看对象.__dict__update的使用
一、字典的update方法
1.描述dict.update()
update() 函数把字典 dict2 的键/值对更新到 dict 里
2.语法
dict.update(dict2)
3.返回值
该方法没有任何返回值
4.栗子
tinydict = {'Name': 'Zara', 'Age': 7} tinydict2 = {'Sex': 'female' } tinydict.update(tinydict2) print ("Value : %s" % tinydict) # Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}
二、.__dict__ 查看对象的属性
方法: obj.__dict__
class TestClass: """My class""" def __init__(self, num: int, total: int): """init""" self.num = num self.total = total if __name__ == '__main__': test = TestClass(num=3, total=10) print(test.__dict__) # {'num': 3, 'total': 10}
二、obj.__dict__.update()
由上面的分段知识点,可以知道update()是对前面的字典进行批量更新内容的
outer_dict = {"owner_name": "zhangsan"} class TestClass: """My class""" inner_dict = {"addr": "SH"} def __init__(self, num: int, total: int): """init""" self.num = num self.total = total if __name__ == '__main__': test = TestClass(num=3, total=10) print("print1:", test.__dict__) # {'num': 3, 'total': 10} test.__dict__.update(outer_dict) print("print2:", test.__dict__) test.__dict__.update(test.inner_dict) print("print3:", test.__dict__) """ result: print1: {'num': 3, 'total': 10} print2: {'num': 3, 'total': 10, 'owner_name': 'zhangsan'} print3: {'num': 3, 'total': 10, 'owner_name': 'zhangsan', 'addr': 'SH'} """
分类:
知识点
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类