如何增加方法中的值(数字)并减少Python中类中定义的值?

时间:2014-06-14 00:05:05

标签: python

我在python中制作游戏,我需要创建一个方法来增加/减少我在类中定义的值。该方法接收一个数字,我必须修改另一个。这是我的代码:

class Ant:
    def __init__(self, name, steps, health, alcohol, state):
        self.name = name
        self.steps = []
        self.health = 100
        self.alcohol = 0
        self.state = state

我需要修改健康状况..请帮帮我

2 个答案:

答案 0 :(得分:2)

使用单个参数定义方法并修改self.health

class Ant:
    def __init__(self, name, steps, health, alcohol, state):
        self.name = name
        self.steps = []
        self.health = 100
        self.alcohol = 0
        self.state = state

    def add_health(self, value):
        self.health += value

    # bonus
    def drink(self, value):
        self.alcohol += value
        self.health -= value

答案 1 :(得分:1)

你可以创建一些从Ant生命值中减去的函数。例如:

class Ant:
    def __init__(self, name, steps, health, alcohol, state):
        self.name = name
        self.steps = []
        self.health = 100
        self.alcohol = 0
        self.state = state

    def damage(self, amount):
        self.health -= amount