Answer the question
In order to leave comments, you need to log in
How to delete an instance of a class in a class in Python?
Is it possible to remove it at the specified location in the code?
class Hero:
def __init__(self):
self.name = input("name? ")
self.health = 100
def blast(self, enemy):
damage = 55
enemy.hurt(damage)
def hurt(self, damage):
self.health -= damage
if self.health <= 0:
# в этом месте экземпляр класса должен удаляться
# (в данном примере должен удалиться экземпляр person2)
else:
print(self.name + ": you hurt me! i have %d health" % self.health)
person1 = Hero()
person2 = Hero()
person1.blast(person2)
person1.blast(person2)
Answer the question
In order to leave comments, you need to log in
How is it - you want to remove it from an instance of a class?
The task is solved by adding a property of the is_dead class and checking this state from the outside. Upon discovery of this fact, it is possible, but only if you really want to, make person2 = None - that's the deletion.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question