0

I was doing this Pokemon project on Codecademy, and it asked me to do something that I was completely unable to think of, as I don't have much practice on OOPS and python.

How can I set is_knocked_out = True, without calling any method on my instance? I think that my code should know automatically when the health of pokemon has become zero and automatically change its attribute is_knocked_out to True. I searched online but didn’t find any definitive solution maybe it has something to do with decorators.

Can someone please explain me how to do this, because I think I might have hit a wall here.

I have written the following code so far:

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")
2
  • Just assign True to that attribute: p = Pokemon( ... ); p.is_knocked_out = True Commented May 28, 2020 at 16:07
  • I mean when i further write this code and the health of my pokemon decreases and eventually raches zero i don't want to explicitly do that, but i want that it happens automatically when health reaches zero Commented May 28, 2020 at 16:09

1 Answer 1

1

A good approach is to make is_knocked_out a property so its value can always be computed from curr_health:

class Pokemon:
    ...

    @property
    def is_knocked_out(self):
        return self.curr_health <= 0
Sign up to request clarification or add additional context in comments.

2 Comments

If i make it a property then it cannot remain an attribute right, we can just access it as attribute. Also in this case i need to do "instance.is_knocked_out", then only it will set it to True, cannot my code auto assign that in some way such that when health = 0, is_knocked_out already becomes true?
@BhavikRoopchandani It's exactly as you describe, every time you access is_knocked_out it will be computed dynamically based on curr_health. So if curr_health <= 0 then is_knocked_out is True.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.