AttributeError:“NoneType”对象在python中没有基于文本的交互故事属性“get”

2024-06-10 01:08:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图用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'

Tags: oftheinfromgetifmainprint
3条回答

正如前面提到的其他答案,您引用的是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

代码结构中有两个关键问题:

  1. 你没有验证输入。i、 如果用户输入“退出”,它将崩溃所有相同的。你至少应该有这样的基本检查:

    while True:
        user_choice = input("Select a choice: ")
        if user_choice in sceneData.get('choices'): break
        print('That was an invalid choice, try again.')
    
  2. 你并不是真的在用输入的选项做任何事情。在您的代码中没有包含键"Enter the Tomb..."的内容,并且它被.get("Enter the Tomb...")方法限制为失败。

您可以在approachdict中引用index个选项并获得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))

有很多方法可以解决这个问题。这取决于你的喜好。你知道吗

当您根据用户输入(sceneData = story.get(user_choice))重新分配屏幕数据时,您不能确保输入的内容是有效的。如果他们输入了您没有屏幕数据的内容,您将从那里的.get()调用返回None,然后当您尝试访问screenData[screenText]时,您将得到NoneType错误。你知道吗

这里的问题是您没有赋值,因为其中没有与所提供的任一选项匹配的键,有效地将sceneData设置为None

然后,在下一次循环迭代中,print(sceneData.get('choices')出错,因为sceneData现在是None,不再是dict。你知道吗

story.get(user_choice)

这引用了storydict:

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
}

如您所见,story中没有与choices列表值匹配的键。你知道吗

您可能需要将多个选项映射到下一个场景;

例如

choices: {
    1: { 'choice-text': 'Enter the Tomb of Horrors!, 'nextScene': 'someScene' }
}

然后让用户输入所选的数字,并编写一些代码,根据nextScene键设置下一个场景。你知道吗

相关问题 更多 >