首页 > 解决方案 > 获取字典中的值

问题描述

我对python相当陌生,我正在做一个角色扮演游戏来练习我正在学习的东西。我有一个项目字典,我想得到其中一个的名称,但是当我调用它时,我收到一条消息:

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"]

有谁知道我做错了什么?在此先感谢您的时间。

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

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

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

标签: pythondictionary

解决方案


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


推荐阅读