gpt4 book ai didi

python - 在方法中编辑字典值

转载 作者:太空狗 更新时间:2023-10-30 02:44:34 26 4
gpt4 key购买 nike

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

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)
}

如何在函数内部编辑 The owned 值?

最佳答案

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

关于python - 在方法中编辑字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28862721/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com