【问题标题】:How can I update a dictionary from within a class method?如何从类方法中更新字典?
【发布时间】:2020-08-14 20:04:01
【问题描述】:

我正在尝试编写一些基本的类和交互来练习并最终将其变成一个工作游戏(类似于 OGame)。在我的代码中,每个玩家都有一些船(我希望它们是类而不是字典,但也不能让它工作)和他们自己的键。我希望字典通过使用 build_ships() 函数来更新船舶数量及其类型,这样做感觉是正确的做法,但目前无法正常工作......

免责声明:总的来说,我在编码方面还很陌生,但找不到任何可以很好地扩展的好的解决方案,或者这种情况的最佳结构是什么。

class Player:
    def __init__(self, name, ships=None):
        self.name = name
        if ships is None:
            self.ships = {}
        else:
            self.ships = ships

    def build_ships(self, ship, quantity):
        self.ships[ship] = quantity


small_cruiser = {
"name":'SMALL CRUISER',
"size":5,
"attack":10,
"defense":7,
"speed":30
}

big_cruiser = {
"name":'BIG CRUISER',
"size":7,
"attack":15,
"defense":9,
"speed":25
}

player_1 = Player('TheLegend27')
player_1.build_ships(small_cruiser, 5)

【问题讨论】:

  • 把船变成类。

标签: python class dictionary methods


【解决方案1】:

您不能将字典用作另一个字典中的键,因为字典是可变的并且字典键必须是可散列的(不可变的)。

在我看来,self.ships 是船舶列表而不是字典更有意义。然后您的 build_ships 方法只需将船舶附加到该列表即可。

考虑以下代码:

class Player:
    def __init__(self, name, ships=None):
        self.name = name
        if ships is None:
            self.ships = []
        else:
            self.ships = ships

    def build_ships(self, ship, quantity):
        for _ in range(quantity):
            s = ship.copy()
            self.ships.append(s)


small_cruiser = {
    "name":'SMALL CRUISER',
    "size":5,
    "attack":10,
    "defense":7,
    "speed":30
}

big_cruiser = {
    "name":'BIG CRUISER',
    "size":7,
    "attack":15,
    "defense":9,
    "speed":25
}

player_1 = Player('TheLegend27')
player_1.build_ships(small_cruiser, 5)

请注意,我们需要添加行 s = ship.copy() 以便创建作为参数传入 build_ships 的原始字典的副本。否则,您将一遍又一遍地附加 same 字典,并且对 self.ships 中的任何字典所做的任何修改都会反映在其他字典上。

【讨论】:

  • 如果属性固定,元素可能不需要复制。
  • @Barmar 同意,但是如果他说,从任何字典中删除一个键,等待 OP 下线仍然是一个令人讨厌的惊喜。无论如何,实际最好的解决方案是把船变成合适的等级。
  • 我认为这就是他的意图,因为他只是想分配一个数量变量。另一种可能性是这是{ship: xxx, quantity: N} 的列表
【解决方案2】:

字典中的键必须是可散列的。因此,您不能将字典作为第二个字典中的键。 一种方法是,如果您知道船只的名称是唯一的,那么您可以只使用 Player 对象来维护名称和计数。

def build_ships(self, ship, quantity):
        self.ships[ship] = quantity

调用者:

player_1.build_ships("SMALL CRUISER", 5)

然后你可以有一个单独的字典来维护船的类型,比如:

ships = {"SMALL CRUISER":{"size":5,
                          "attack":10,
                          "defense":7,
                          "speed":30},
         "BIG CRUISER":{"size":7,
                        "attack":15,
                        "defense":9,
                        "speed":25},
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-04
    • 2013-02-15
    • 2021-12-30
    • 2022-08-12
    • 1970-01-01
    • 2012-11-19
    • 2011-05-08
    • 2020-09-14
    相关资源
    最近更新 更多