A
A
Aman2019-11-12 22:06:18
Python
Aman, 2019-11-12 22:06:18

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

3 answer(s)
_
_, 2019-11-12
@robick231

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.

Z
Zolg, 2019-11-12
@Zolg

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
..

A
Andy_U, 2019-11-12
@Andy_U

Because __init__ has already been called. And the second time, no. The effect you need can be achieved using, for example, property.
PS Well, it's generally not good to use class members directly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question