Python:如何阻止变量超过值?

时间:2015-11-24 01:43:25

标签: python

我知道这听起来很愚蠢而且可能非常简单,但我只需要直接,快速的方式,因为我可能需要在整个代码中使用它。 我会在这里粘贴我的代码,也请忽略它继续关于Minecraft的事实;我个人无法忍受这场比赛,但这在我的学校里却是一个笑话。不过,实际的代码真的是我只是想为我的GCSE做好准备。是的,我知道它并不是最好的,但我只学了一个星期的python。 Pastebin to my code: http://pastebin.com/QWtWJMvV

这部分代码是我阻止我的健康的方式。变量超过20:if health < 20: health = 20。无论这是否是最有效的方式,或者它是否有效都超出了我的范围。

最后一件事,如果有人能给我一个更简单的写作方式,那就太棒了:

healthRecover0 = (randint(1,10))
if health == 20:
    healthRecover0 = (randint(0,0))
elif healthRecover0 == 1:
    health + 1
elif healthRecover0 == 2:
    health + 2
elif healthRecover0 == 3:
    health + 3
elif healthRecover0 == 4:
    health + 4
elif healthRecover0 == 5:
    health + 5
elif healthRecover0 == 6:
    health + 6
elif healthRecover0 == 7:
    health + 7
elif healthRecover0 == 8:
    health + 8
elif healthRecover0 == 9:
    health + 9
elif healthRecover0 == 10:
    health + 10

因为那太荒谬了。

1 个答案:

答案 0 :(得分:0)

pythonic方式是使用@property装饰器。您可以在设置器中提供检查最大健康状况的逻辑:

class Monster(object):

    def __init__(self, initial_health=20, max_health=20):
        # Private property which stores the actual health
        self._health = initial_health
        self.max_health = 20

    @property
    def health(self):
        return self._health

    @health.setter
    def health(self, value):
        if value > self.max_health:
            value = self.max_health
        self._health = value

这样,不能为值分配大于最大可能值的值:

a = Monster()

assert a == 20   # Intitial value is 20

a.health = 10
assert a == 10   # Changed to 10

a.health = 30
assert a == 20   # we set it to 30 but is capped to 20 max