Why won\'t this work? I\'m trying to make an instance of a class delete itself.
>>> class A():
def kill(self):
del self
>>>
If you're using a single reference to the object, then the object can kill itself by resetting that outside reference to itself, as in:
class Zero:
pOne = None
class One:
pTwo = None
def process(self):
self.pTwo = Two()
self.pTwo.dothing()
self.pTwo.kill()
# now this fails:
self.pTwo.dothing()
class Two:
def dothing(self):
print "two says: doing something"
def kill(self):
Zero.pOne.pTwo = None
def main():
Zero.pOne = One() # just a global
Zero.pOne.process()
if __name__=="__main__":
main()
You can of course do the logic control by checking for the object existence from outside the object (rather than object state), as for instance in:
if object_exists:
use_existing_obj()
else:
obj = Obj()
This is something I have done in the past.
Create a list of objects, and you can then have objects delete themselves with the list.remove()
method.
bullet_list = []
class Bullet:
def kill_self(self):
bullet_list.remove(self)
bullet_list += [Bullet()]