简体   繁体   English

如何在一个方法中增加一个值(num)并减少在Python类中定义的另一个值?

[英]How do I increase a value (num) in a method and decrease another defined in a class in Python?

I am making a game in python and I need to create a method to increase/decrease a value that I define in a class. 我正在用python做游戏,我需要创建一种方法来增加/减少我在类中定义的值。 The method receives a number and with that i have to modify the other. 该方法收到一个数字,我必须修改另一个数字。 This is my code: 这是我的代码:

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

I need to modify the health.. Help me please 我需要修改健康状况。请帮助我

Define a method with a single argument and modify the self.health : 使用单个参数定义方法并修改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

You can make some function that subtracts from the Ant s health. 您可以创建一些从Ant的健康中减去的功能。 For example: 例如:

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

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

相关问题 如何使用 python 计算值列表中的百分比增加或减少 - How do i calculate the percentage increase or decrease in a list of values with python 如何在Python 2.7中用另一个类装饰实例方法? - How do I decorate an instance method with another class in Python 2.7? 如何从 Python 中的另一个文件调用类方法? - How do I call a class method from another file in Python? 减少 Python 中“i”的值 - Decrease value of "i" in Python 如何调用类整数并增加其值? - How do I call a class integer and add increase it's value? 如何访问之前在另一个 class 中定义的 class 中的变量? - How do I access a variable in a class that was defined before in another class? 如何打印在python中不同类的方法中定义的变量值? - How can i print variable value defined in the method of a different class in python? 在python中多线程时如何增加变量值 - How do I increase variable value when multithreading in python 如何使方法从Python同一类中的另一个方法获取值 - How can I make a method takes the value(s) from another method from within the same class in Python Python 类与另一个类在同一个文件中定义 - 如何访问文件中稍后定义的类? - Python class defined in the same file as another class - how do you get access to the one defined later in the file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM