在方法中编辑dict值

时间:2015-03-04 19:03:34

标签: python function dictionary immutability key-value

我有一个程序用于保存游戏中对象的统计数据,如下所示:

Weapon = namedtuple("Weapon", ["owned", "damage", "price", "accuracy"])

weapons = {
    "fists":    Weapon(True, 2, None, 75),
    "knife":    Weapon(False, 4, 50, 95),
    "sword":    Weapon(False, 6, 100, 90),
    "pistol":   Weapon(False, 8, 250, 65),
    "rifle":    Weapon(False, 10, 500, 80),
    "rpg":      Weapon(False, 20, 1000, 100)
}

如何编辑函数内部的owned值?

2 个答案:

答案 0 :(得分:3)

namedtuple是不可变的。为什么不使用课程?您的代码将更清晰,更有条理,更模块化,更易于重用。

class Weapon:
    def __init__(self, owned, damage, price, accuracy):
        self.owned = owned
        self.damage = damage
        self.price = price
        self.accuracy = accuracy

    def flip_weapon_owned_value(self):
        self.owned = False if self.owned else True
        print "\n", self.owned


weapons = {
    'fists' :  Weapon(True, 2, None, 75),
    'knife' :  Weapon(False, 4, 50, 95),
    'sword' :  Weapon(False, 6, 100, 90),
    'pistol' : Weapon(False, 8, 250, 65),
    'rifle' :   Weapon(False, 10, 500, 80),
    'rpg' :     Weapon(False, 20, 1000, 100)
}

> weapons['fists'].flip_weapon_owned_value()
> False

> weapons['fists'].flip_weapon_owned_value()
> True

答案 1 :(得分:2)

namedtuple允许您使用更新的值克隆它。见_replace。它以下划线开头,因此不会与任何属性名称冲突。

您需要将此更新的克隆重新分配给字典键:

weapons = ... # as above

def main():
    do_something(weapons)

def do_something(weapons):
    weapons['fists'] = weapons['fists']._replace(owned=False)