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

学习LPTHW ex43.py时遇AttributeError错误,OOP新手求助

解决LPTHW练习43中的AttributeError: 'list' object has no attribute 'get'

Hey there! 刚入门OOP碰到这种问题太正常了,咱们先把这个错误拆明白:

AttributeError: 'list' object has no attribute 'get'

这个报错直接点出了问题核心:你把一个**列表(list)当成字典(dict)**来调用方法了——get()是字典专属的方法,列表根本没有这个功能。看错误栈里的File "ex43.py", line 197, in next_scene return Map.scenes.get(scene_name),说明你定义的Map.scenes是个列表,而不是练习要求的字典。

回忆下LPTHW练习43的设计,Map类的scenes应该是一个场景名称到场景对象的映射字典,正确的写法大概是这样:

class Map:
    # 用大括号定义字典,键是场景名称字符串,值是对应的场景实例
    scenes = {
        'central_corridor': CentralCorridor(),
        'laser_weapon_armory': LaserWeaponArmory(),
        'the_bridge': TheBridge(),
        'escape_pod': EscapePod(),
        'death': Death()
    }
    start_scene = 'central_corridor'

    # 其他方法...

而你大概率是不小心把字典写成了列表,比如:

class Map:
    # 错误:用了列表的方括号,没有键值对映射
    scenes = [
        CentralCorridor(),
        LaserWeaponArmory(),
        TheBridge(),
        EscapePod(),
        Death()
    ]

修复步骤:

  1. 打开你的ex43.py,找到Map类的scenes定义
  2. 把包裹内容的方括号[]改成大括号{}
  3. 给每个场景对象加上对应的场景名称键,形成'场景名': 场景实例的键值对结构
  4. 确认start_scene的值是scenes字典里存在的某个键(比如'central_corridor')

这样修改后,next_scene方法里的Map.scenes.get(scene_name)就能正常从字典里取出对应的场景对象,报错就会消失啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:28:25