You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码报错AttributeError:'dict'对象属性'update'为只读求排查

问题根源与解决方案

嘿,我一眼就看出问题所在啦!你这里犯了个典型的新手错误——把字典的内置方法update当成普通属性来直接赋值了。

错误原因

字典的update是内置方法,它的作用是接收一个字典参数,把参数里的键值对合并到原字典中。而你写的point1back.update = {'nextHop':point1Fwd, 'direction':1, 'distance':0}是在试图给这个只读的方法属性赋值,Python不允许修改内置方法的引用,所以直接抛出了AttributeError: 'dict' object attribute 'update' is read-only错误。

另外还要提醒你:代码里的point1Fwd和定义的变量point1fwd大小写不一致,这会引发NameError,这个细节也要修正哦!

修正后的代码

map = []
point1back = {}
point1fwd = {}
# 正确调用update方法,传入要合并的字典作为参数
point1back.update({'nextHop': point1fwd, 'direction': 1, 'distance': 0})
point1fwd.update({'nextHop': point1fwd, 'direction': 3, 'distance': 160})
map.append(point1back)
map.append(point1fwd)

或者更简洁的方式,直接在初始化字典的时候就把键值对写进去,省去update步骤:

map = []
# 先初始化point1fwd,避免后续引用时变量未定义
point1fwd = {'nextHop': point1fwd, 'direction': 3, 'distance': 160}
point1back = {'nextHop': point1fwd, 'direction': 1, 'distance': 0}
map.append(point1back)
map.append(point1fwd)

内容的提问来源于stack exchange,提问作者duke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:12:56