Answer the question
In order to leave comments, you need to log in
Why doesn't the variable in __init__ change?
Why is the is_alive variable not changing?
class Warrior:
def __init__(self, health=50, attack=5):
self.health = health
self.attack = attack
#
self.is_alive = True
if self.health <= 0:
self.is_alive = False
at = Warrior()
at.health = 0
print(at.health, at.is_alive)
>>> 0, True
Answer the question
In order to leave comments, you need to log in
In your code, the health check is_alive change happens in the __init__ method -> __init__ is only called once when the object is created. Therefore, once you have created an object by calling at = Warrior() , the check will no longer be called. Make a separate method for reducing health and add is_alive to False in it when it drops to zero.
In this case, if you call at = Warrior(health=0) - your check will work and Warrior will be born dead, no matter how sad it may be.
Well, 50 is more than 0, so True
and what result did you expect?
def __init__(self, health=50 , attack=5):
...
if self.health > 0:
self.is_alive = True
..
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question