Python object deleting itself

后端 未结 14 1874
一向
一向 2020-11-27 04:23

Why won\'t this work? I\'m trying to make an instance of a class delete itself.

>>> class A():
    def kill(self):
        del self


>>>          


        
相关标签:
14条回答
  • 2020-11-27 05:03

    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()
    
    0 讨论(0)
  • 2020-11-27 05:03

    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()]
    
    0 讨论(0)
提交回复
热议问题