python - AttributeError:'NoneType'对象没有属性'get'-python中基于文本的交互式故事
问题描述
我正在尝试在 python 中制作基于文本的交互式故事,但我不断收到此错误:AttributeError: 'NoneType' object has no attribute 'get'
我的代码很长,所以我将发布出现此错误的部分故事:
approach = {'sceneText': "Following the map from the old man in the tavern, you arrive at a large hill,"
"covered with ancient standing stone forming the shape of a skull if viewed from a high vantage "
"point.", \
'choices': ["Enter the Tomb of Horrors!", "Run Away! (Wuss)"], 'nextScene':["Entrance", "Runaway"]}
def main():
story = {"Approach":approach, "Runaway":runaway, "Entrance":entrance, "Sealed":sealed, "Collapse":collapse, "Hallway":hallway, "Demon":demon, "PurpleHaze":purplehaze, "Damn":damn, "PitTrap":pittrap, "Gargoyle":gargoyle, "MoreSpikes":morespikes}
sceneData = story['Approach']
while(True):
#.get metehod returns value for the given key
print(sceneData.get('sceneText'))
print("Choices: ")
for choice in sceneData.get('choices'):
print(choice)
user_choice = input("Select a choice: ")
sceneData = story.get(user_choice)
if __name__ == '__main__':
main()
运行时:
Following the map from the old man in the tavern, you arrive at a large hill,covered with ancient standing stone forming the shape of a skull if viewed from a high vantage point.
Choices:
Enter the Tomb of Horrors!
Run Away! (Wuss)
Select a choice: Enter the Tomb of Horrors!
Traceback (most recent call last):
File "story.py", line 75, in <module>
main()
File "story.py", line 67, in main
print(sceneData.get('sceneText'))
AttributeError: 'NoneType' object has no attribute 'get'
解决方案
正如提到的其他答案,您正在引用一个不存在的密钥,story
这就是它给您错误的原因。简而言之,这就是您的代码当前的运行方式:
# Iteration 1
print(sceneData.get('sceneText'))
# evals to approach.get('sceneText'))
# prints flavour text
print("Choices: ")
for choice in sceneData.get('choices'):
# evals to approach.get('choices')
print(choice)
# print list of choices within approach dict
user_choice = input("Select a choice: ")
# user inputs "Enter the Tomb..."
sceneData = story.get(user_choice)
# evals to sceneData = story.get("Enter the Tomb...")
# Since story does not have an "Enter the Tomb" key, it returns None by default.
# sceneData = None
# ---
# Iteration 2
print(sceneData.get('sceneText'))
# evals to None.get('sceneText'))
# errors out
您的代码结构中有两个关键问题:
您没有验证输入。即如果用户输入“退出”它会崩溃一样。你应该至少有一个这样的基本检查:
while True: user_choice = input("Select a choice: ") if user_choice in sceneData.get('choices'): break print('That was an invalid choice, try again.')
您并没有真正对输入的选择做任何事情。您的代码中没有任何内容包含密钥
"Enter the Tomb..."
,并且它必然会因方法而失败.get("Enter the Tomb...")
。
您可以index
在您的 dict 中引用选项approach
并获取nextScene
(这需要更多的工作):
scene_index = sceneData.get('choices').index(user_choice)
sceneData = story.get('nextScene')[scene_index]
或者您可以重组您的代码,以便choices
如下dicts
所示:
approach = {...
'choices': {
"Enter the Tomb of Horrors!": "Entrance",
"Run Away! (Wuss)": "Runaway"
}
}
当需要时choices
,调用它:
sceneData.get('choices').keys()
需要时nextScene
,调用它:
sceneData = story.get(sceneData.get('choices').get(user_choice))
有很多方法可以解决这个问题。这取决于你的喜好。
推荐阅读
- django - ImportExportModelAdmin 给出错误 django.template.exceptions.TemplateDoesNotExist: admin/import_export/change_list_import_export.html
- qt - QML PageIndicator 适合矩形的大小
- python - 无法在系统上安装 PyAudio
- jquery - 在 bing 地图中为不同的邮政编码添加图钉
- flutter - 引发了另一个异常:错误:找不到正确的提供程序
在此 BlocSelector 上方 小部件 - c# - .NET 用于列表或单个项目的自定义 Json 转换器
- asp.net-mvc - 使用引导日期选择器对 MM/YYYY 进行 ASP NET MVC 客户端验证
- python - Tkinter .bind 无法绑定使用函数创建的按钮
- excel - 如何创建 COUNTIF 以查找包含长字符串的列的单元格中的文本
- github - 使用 GitHub NPM 注册表时出现 401 Unauthorized