将字典添加到班级

时间:2018-10-04 10:28:34

标签: python class dictionary

我想让角色从字典中将物品添加到其库存中,但是当我添加它们时,它只给我“价值”的回报,而不是“键”的回报。我想将两者都用于游戏的不同部分,例如“您拿着'钥匙',它确实'珍视'伤害”。

我想我知道这是在添加字典“值”,因为我的库存类型是“列表”,但是很难找到添加字典项的简单方法。

预先感谢您的帮助!

from random import randint

class Character:
    # Instantiates each character with personality traits
    def __init__(self, name, health, lives, gender, inventory):
        self.name = name
        self.health = int(health)
        self.lives = int(lives)
        self.gender = gender
        self.inventory = []


inventoryitems = {
    'Breadstick': randint(0,5), 
    'Magic Axe': randint(50,100), 
    'Tiny Fists': randint(0,25),
    'Sword': randint(15,30)
    }

player = Character("Kate", 100, 3, 'female',None)

player.inventory.append(inventoryitems['Magic Axe'])
player.inventory.append(inventoryitems['Breadstick'])
print(player.inventory)

2 个答案:

答案 0 :(得分:1)

您可以使用函数items()来同时遍历键和值:

from random import randint

class Character:
    # Instantiates each character with personality traits
    def __init__(self, name, health, lives, gender, inventory):
        self.name = name
        self.health = int(health)
        self.lives = int(lives)
        self.gender = gender
        self.inventory = []


inventoryitems = {
    'Breadstick': randint(0,5), 
    'Magic Axe': randint(50,100), 
    'Tiny Fists': randint(0,25),
    'Sword': randint(15,30)
}

player = Character("Kate", 100, 3, 'female',None)

# item will be a (key, value) pair
for item in inventoryitems.items():
    player.inventory.append(item)

# or if you only want to add specific items
items_to_add = ['Breadstick', 'Magic Axe']
for item in items_to_add:
    player.inventory.append((item, inventoryitems[item]))

print(player.inventory)

将打印例如

[('Breadstick', 5), ('Magic Axe', 51), ('Tiny Fists', 21), ('Sword', 17), ('Breadstick', 5), ('Magic Axe', 51)]

请注意,两次添加项目不会将新的随机值应用于每个随机值,这可能不是您想要的。

答案 1 :(得分:1)

在类中使用字典很简单,然后可以使用player.inventory.keys()按名称生成项目列表,也可以稍后通过player.inventory ['object_name ']

from random import randint

class Character:
    # Instantiates each character with personality traits
    def __init__(self, name, health, lives, gender, inventory):
        self.name = name
        self.health = int(health)
        self.lives = int(lives)
        self.gender = gender
        self.inventory = {}


inventoryitems = {
    'Breadstick': randint(0,5), 
    'Magic Axe': randint(50,100), 
    'Tiny Fists': randint(0,25),
    'Sword': randint(15,30)
    }

player = Character("Kate", 100, 3, 'female',None)

player.inventory['Magic Axe'] = inventoryitems['Magic Axe']
player.inventory['Breadstick'] = inventoryitems['Breadstick']
print(player.inventory)