如何为同一个对象提供不同的值?

时间:2017-10-27 12:29:33

标签: python-3.x

我是Python新手并试图制作简单的钓鱼游戏。我希望将“鲑鱼”这个对象多次添加到库存中,并使用不同的“重量”和“抗拒”值。使用下面的inventory.add_item函数,似乎只有一个项目被添加到库存中,或者相同的项目被添加两次并具有相同的值。

我如何能够获得具有不同值的相同类型的对象?

import random

class Inventory(object):
    def __init__(self):
        self.fishes = {}

    def add_item(self, fish):
        self.fishes[fish.species] = fish

    def print_items(self):
        print('\t'.join(['Weight', 'Resist', 'Species']))
        for fish in self.fishes.values():
            print('\t'.join([str(x) for x in [fish.weight, fish.resist, fish.species]]))

inventory = Inventory()

class Fish(object):

    def __init__(self, weight, resist, species):

        self.weight = weight
        self.resist = resist
        self.species = species

salmon = Fish(random.randint(2, 10), random.randint(5, 7), 'Atlantic Salmon')

print('Going fishing...\nCaught a Salmon!')

inventory.add_item(Fish(salmon.weight, salmon.resist, salmon.species))
inventory.add_item(Fish(salmon.weight, salmon.resist, salmon.species))

inventory.print_items()

1 个答案:

答案 0 :(得分:0)

试试这个:

 salmon = Fish(random.randint(2, 10), random.randint(5, 7), 'Atlantic Salmon')
 salmon2 = Fish(random.randint(2, 10), random.randint(5, 7), 'Atlantic Salmon2')

 print('Going fishing...\nCaught a Salmon!')

 inventory.add_item(salmon)
 inventory.add_item(salmon2)

 inventory.print_items()

首先,字典的键必须是唯一的:

fish.species

也是你添加的对象,因为关键......