在字典中获取值

时间:2018-10-02 17:35:41

标签: python dictionary

我对python来说还很陌生,我正在做一个RPG来练习我正在学习的内容。我有一个项目字典,我想获取其中一个的名称,但是当我调用它时,我收到一条消息:

You don't have any<classes.inventory.Item object at 0x7f52e39bce48>left!

我的词典是这个:

player_items = [{"item":potion, "quantity": 15},
                {"item":hipotion, "quantity": 10},
                {"item":superpotion, "quantity": 8},
                {"item":elixir, "quantity": 3},
                {"item":hielixir, "quantity":1},
                {"item":grenade, "quantity": 12}]

item = player.items[item_choice]["item"]
player.items[item_choice]["quantity"] -= 1

if player.items[item_choice]["quantity"] == 0:
    print(bcolors.FAIL+"\n"+"You don't have any"+str(item)+"left!"+bcolors.ENDC)

class Item:
    def __init__(self, name, type, description, prop):
        self.name = name
        self.type = type
        self.description = description
        self.prop = prop

class Person:
    def __init__(self, hp, mp, atk, df, magic, items):
        self.maxhp = hp
        self.hp = hp
        self.maxmp = mp
        self.mp = mp
        self.atkhigh = atk+10
        self.atklow = atk-10
        self.df = df
        self.items = items
        self.magic = magic
        self.actions = ["Attack", "Magic", "Items"]

有人知道我在做什么错吗?预先感谢您的宝贵时间。

编辑:发现错误。我需要了解更多。我只需要在调用项目时添加name属性:

print(bcolors.FAIL+"\n"+"You don't have any"+str(item.name)+"left!"+bcolors.ENDC)

对不起,我浪费了你的时间。

2 个答案:

答案 0 :(得分:2)

例如,

item不是字符串"potion";它是对代表药水的Item实例的引用。您需要为__str__类提供适当的Item方法。

答案 1 :(得分:0)

@ Ifsalazar2010欢迎使用python。这是我认为您可能做错了的几件事。

首先,您的dict值必须为字符串,否则python会尝试将其查找为对象。因此,写"potion"而不是potion

player_items = [{"item":"potion", "quantity": 15},
            {"item":"hipotion", "quantity": 10},
            {"item":"superpotion", "quantity": 8},
            {"item":"elixir", "quantity": 3},
            {"item":"hielixir", "quantity":1},
            {"item":"grenade", "quantity": 12}]

接下来,您需要使用适当的对象player_items而不是player.items。您的对象是一个字典列表,您可以按索引调用它,而您尚未定义item_choice。我以索引1为例。

item = player_items[1]["item"]
print(item)
player_items[1]["quantity"] -= 1
print(player_items)

简而言之,似乎您没有在示例中提供细节来复制错误。例如bcolors.FAIL