我正试图用python编写一个基于文本的交互式故事,但我一直遇到这样的错误:AttributeError:'NoneType'对象没有属性'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
中不存在的键,这就是为什么它会给您一个错误。简而言之,这是您的代码当前运行的方式:代码结构中有两个关键问题:
你没有验证输入。i、 如果用户输入“退出”,它将崩溃所有相同的。你至少应该有这样的基本检查:
你并不是真的在用输入的选项做任何事情。在您的代码中没有包含键
"Enter the Tomb..."
的内容,并且它被.get("Enter the Tomb...")
方法限制为失败。您可以在
approach
dict中引用index
个选项并获得nextScene
(这需要更多的工作):或者可以重新构造代码,使
choices
像这样dicts
:当需要
choices
时,用以下命令调用它:当需要
nextScene
时,使用以下命令调用它:有很多方法可以解决这个问题。这取决于你的喜好。你知道吗
当您根据用户输入(
sceneData = story.get(user_choice)
)重新分配屏幕数据时,您不能确保输入的内容是有效的。如果他们输入了您没有屏幕数据的内容,您将从那里的.get()
调用返回None
,然后当您尝试访问screenData[screenText]
时,您将得到NoneType
错误。你知道吗这里的问题是您没有赋值,因为其中没有与所提供的任一选项匹配的键,有效地将
sceneData
设置为None
然后,在下一次循环迭代中,
print(sceneData.get('choices')
出错,因为sceneData现在是None
,不再是dict
。你知道吗story.get(user_choice)
这引用了
story
dict:如您所见,
story
中没有与choices
列表值匹配的键。你知道吗您可能需要将多个选项映射到下一个场景;
例如
然后让用户输入所选的数字,并编写一些代码,根据
nextScene
键设置下一个场景。你知道吗相关问题 更多 >
编程相关推荐