我收到此错误 - > TypeError:字符串索引必须是整数

时间:2018-05-03 00:12:15

标签: python python-3.x oop compiler-errors

我试图通过制作基于文本的RPG来学习面向对象的编程,如下所示。与我的问题相关的部分是:

    def equipArmor(self):
        for armor in self.armorsOwned:
            select = 1
            if self.armor == armor:
                print(str(select) + ". " + str(armor["Name"]) + " (Equipped)")
            else:
                print(str(select) + ". " + str(armor["Name"]))
            select += 1
        armor_choice = input("Type the name of the armor you would like to equip\n")
        for i in self.armorsOwned:
            if armor_choice == i["Name"]:
                if self.armor == i:
                    print("You already have that equipped")
                else:
                    self.armor = i["Name"]
                    print("You equipped the {}".format(i["Name"]))
                    self.maxhp += i["Effect"]

class Shop:

    armors = {"BronzeArmor":{"Name": "Bronze armor",
                             "Cost": 30,
                             "Effect": 10},
              "SilverArmor":{"Name": "Silver armor",
                             "Cost": 75,
                             "Effect": 20}}

以下是其他内容,以便您了解我的代码的上下文:

import time
import sys

class Player:

    def __init__(self):
        self.level = 1
        self.exp = 0
        self.gold = 0
        self.maxhp = 20
        self.hp = self.maxhp
        self.attack = 1
        self.weapon = ""
        self.armor = ""
        self.weaponsOwned = {}
        self.armorsOwned = {}

    def checkHp(self):
        self.hp = max(0, min(self.hp, self.maxhp))

    def deadCheck(self):
        if self.hp == 0:
            print("You died!")
            sys.exit()

    def equipArmor(self):
        for armor in self.armorsOwned:
            select = 1
            if self.armor == armor:
                print(str(select) + ". " + str(armor["Name"]) + " (Equipped)")
            else:
                print(str(select) + ". " + str(armor["Name"]))
            select += 1
        armor_choice = input("Type the name of the armor you would like to equip\n")
        for i in self.armorsOwned:
            if armor_choice == i["Name"]:
                if self.armor == i:
                    print("You already have that equipped")
                else:
                    self.armor = i["Name"]
                    print("You equipped the {}".format(i["Name"]))
                    self.maxhp += i["Effect"]

class Enemy:

    def __init__(self, attack, maxhp, exp, gold):
        self.exp = exp
        self.gold = gold
        self.maxhp = maxhp
        self.hp = maxhp
        self.attack = attack

    def checkHp(self):
        self.hp = max(0, min(self.hp, self.maxhp))

    def enemyDeadCheck(self):
        if self.hp == 0:
            return True

class Shop:

    armors = {"BronzeArmor":{"Name": "Bronze armor",
                             "Cost": 30,
                             "Effect": 10},
              "SilverArmor":{"Name": "Silver armor",
                             "Cost": 75,
                             "Effect": 20}}

character = Player()
character.armorsOwned.update(Shop.armors["BronzeArmor"])
character.equipArmor()

我想要做的就是打印出我拥有的所有装甲,打印"装备"如果配备它,在它旁边,从输入接收装甲的名称,检查它是否已经装备,如果没有装备则装备它。但是,标题中提到的错误阻止了我这样做。为什么会这样,什么是字符串指示?

3 个答案:

答案 0 :(得分:1)

循环遍历词典(例如,for i in self.armorsOwned)会返回的可迭代内容,而不是条目。所以i被设置为关键字符串,而不是盔甲字典。

你想把所有循环都转到字典上:

for i in self.armorsOwned.values():

答案 1 :(得分:1)

没有足够的积分发表评论,因此张贴为答案。 当您将列表视为字典时,通常会抛出此错误。

如果您可以包含显示错误的#line以便我可以精确定位,那会很有帮助但是对我来说这看起来很可疑:

self.armorsOwned = {}

如果它只是一本盔甲字典。在这种情况下,这就是你如何提取护甲名称:

        if self.armor == armor:
            print(str(select) + ". " + str(self.armorsOwned[armor]["Name"]) + " (Equipped)")
        else:
            print(str(select) + ". " + str(self.armorsOwned[armor]["Name"]))

您还可以尝试打印这些变量的值,以便在执行任何字符串操作之前查看它们包含的内容:

def equipArmor(self):
        print(self.armorsOwned)
        for armor in self.armorsOwned:
            print(armor)
            select = 1

答案 2 :(得分:0)

TypeError: string indices must be integers是Python中一个非常常见的错误,尤其是在开发过程中。它表示您的变量是一个字符串,但您尝试将其用作字典。

示例:

x = {'Name': 'Bronze Armor'}
print(x['Name']) #    Bronze Armor

x = 'Bronze Armor'
print(x['Name']) #    raises TypeError: string indices must be integers

查看错误的堆栈跟踪,它会告诉您错误的哪一行。