简体   繁体   English

如何在 python 的字典中完成数学和变量赋值?

[英]How do i complete maths and variable assignment inside a dictionary in python?

Player1 = {
    "name":"Bob",
    "attack":7,
    "defence":5,
    "total":Player1["attack"]+Player1["defence"],
}

How do I set total in the dictionary to be attack + defense?如何将字典中的总数设置为攻击+防御?

Unfortunately what you're asking isn't do able as far as I'm aware... you'd be better using a class不幸的是,据我所知,您要问的问题是……您最好使用 class

like this:像这样:

class Player:

    def __init__(self):
        self.name = "Bob"
        self.attack = 7
        self.defence = 5
        self.total = self.attack + self.defence

player = Player()
print(player.total)

What you've got to remember is you've not instantiated the dict when you declare it, so inside the {} you can't call Player1 as it doesn't exist in the context yet.您必须记住的是,您在声明 dict 时并未对其进行实例化,因此在{}内您不能调用Player1 ,因为它在上下文中尚不存在。

By using classes you could also reuse the example above by doing something like:通过使用类,您还可以通过执行以下操作来重用上面的示例:

class Player:

    def __init__(self, name, attack, defence):
        self.name = name
        self.attack = attack
        self.defence = defence
        self.total = self.attack + self.defence

player1 = Player(name="bob", attack=7, defence=5)
player2 = Player(name="bill", attack=10, defence=7)
print(player1.total)
print(player2.total)

EDIT: fixed typo编辑:修正错字

You are currently trying to access Player1 before creating it.您当前正在尝试在创建Player1之前访问它。

You could do:你可以这样做:

Player1 = {
    "name":"Bob",
    "attack":7,
    "defence":5
}
Player1["total"] = Player1["attack"] + Player1["defence"]

However, this is not ideal, because you need to remember to adjust the 'total' field whenever 'attack' or 'defence' change.但是,这并不理想,因为您需要记住在'attack''defence'发生变化时调整'total'字段。 It's better to compute the total value on the fly, since it is not an expensive computation.最好即时计算总值,因为它不是昂贵的计算。

This can be achieved by writing a Player class with a property total .这可以通过编写具有属性totalPlayer class 来实现。

class Player:
    def __init__(self, name, attack, defence):
        self.name = name
        self.attack = attack
        self.defence = defence

    @property
    def total(self):
        return self.attack + self.defence

Demo:演示:

>>> Player1 = Player('Bob', 1, 2)
>>> Player1.name, Player1.attack, Player1.defence, Player1.total
('Bob', 1, 2, 3)

Let's say you don't want to compute value of the key total yourself.假设您不想自己计算键总计的值。 You can initialize it to None (Standard practice. Better than omitting it).您可以将其初始化为None (标准做法。比省略它更好)。

Player1 = {
    "name":"Bob",
    "attack":7,
    "defence":5,
    "total":None
}

Then update it's value later on.然后稍后更新它的值。

Player1["total"] = Player1["attack"] + Player1["defence"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM