-1

I am working on a text adventure game written in Python just for fun (to see if I could do it). I am working on the module for the entities, and am working on a method for them being killed. When an entity is killed, instead of just displaying a kill message and rendering the entity unable to act, I also want its instance to be deleted to conserve memory.

How can I make an instance of the entity class delete itself?

For example (partly pseudocode):

class Entity(object):
    #other methods here

    def kill(self):
       if self.health <= 0:
           self.deleteinstance
           or
           deleteinstance(self)

Thank you in advance for your help.

EDIT: I understand that this is a duplicate, but the answers in all the others reference that objects are deleted when nothing refers to them. My question here is how to make nothing refer to the instance of this class, because without a kill method, presumably the instance will still be in memory with negative health.

jm13fire
  • 185
  • 1
  • 7
  • Python objects are garbage collected. You only need to remove any reference to them and they will be deleted automatically. Google Python Object Lifetime including [this SO post](http://stackoverflow.com/questions/11894045/python-object-lifetime-characteristics) for more. – dawg May 26 '15 at 16:15

1 Answers1

2

Now, why would you do that?

Objects in Python will be garbage collected once nothing points to them, so you need not worry. Otherwise, you should checkout some of the answers in this other SO question: Python object deleting itself.

You could try:

def kill():
    if self.health < 0:
        del self
Community
  • 1
  • 1
Zizouz212
  • 4,908
  • 5
  • 42
  • 66