如何在不调用Python方法的情况下更改类中的属性值?

时间:2020-05-28 16:03:10

标签: python class oop project

我在Codecademy上进行了这个Pokemon项目,它要求我做一些我完全无法想到的事情,因为我对OOPS和python没有太多的练习。

如何在不对实例调用任何方法的情况下设置is_knocked_out = True?我认为我的代码应该在口袋妖怪的生命值变为零时自动知道并自动将其属性is_knocked_out更改为True。 我在网上搜索过,但没有找到任何确定的解决方案,也许与装饰器有关。

有人可以解释一下该怎么做,因为我想我可能在这里碰壁了。

到目前为止,我已经编写了以下代码:

class Pokemon:

    def __init__(self,name,level,ptype,is_knocked_out= False):
        self.name = name
        self.level = level
        self.type = ptype
        self.max_health = level
        self.curr_health = max_health
        self.is_knocked_out = is_knocked_out

    def lose_health(self,loss_amount):
        self.curr_health -= loss_amount
        print(f"{self.name} has now health of {self.curr_health}")

    def regain_health(self,gain_amount):
        self.curr_health += gain_amount
        print(f"{self.name} has now health of {self.curr_health}")

    #@property
    def knock_out(self):
        if self.curr_health <=0:
            self.is_knocked_out = True
            print(f"{self.name} has been knocked out")

1 个答案:

答案 0 :(得分:1)

一种好的方法是将is_knocked_out设为property,以便始终可以根据curr_health计算其值:

class Pokemon:
    ...

    @property
    def is_knocked_out(self):
        return self.curr_health <= 0
相关问题