我在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
我需要修改健康状况..请帮帮我
答案 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