簡體   English   中英

如何在一個方法中增加一個值(num)並減少在Python類中定義的另一個值?

[英]How do I increase a value (num) in a method and decrease another defined in a class in 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

我需要修改健康狀況。請幫助我

使用單個參數定義方法並修改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

您可以創建一些從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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM