首页 > 解决方案 > 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'

标签: pythonpython-3.xtext

解决方案


正如提到的其他答案,您正在引用一个不存在的密钥,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. 您没有验证输入。即如果用户输入“退出”它会崩溃一样。你应该至少有一个这样的基本检查:

    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...")

您可以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))

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


推荐阅读