簡體   English   中英

如何在不調用Python中的方法的情況下更改class中的屬性值?

[英]How to change the attribute value in class without calling the method in Python?

我在 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")

一個好的方法是使is_knocked_out成為一個property ,這樣它的值總是可以從curr_health計算出來:

class Pokemon:
    ...

    @property
    def is_knocked_out(self):
        return self.curr_health <= 0

暫無
暫無

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

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