Python object deleting itself

后端 未结 14 1965
一向
一向 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 04:58

    Realistically you should not need to delete the object to do what you are trying to do. Instead you can change the state of the object. An example of how this works without getting into the coding would be your player fighting a monster and killing the monster. The state of this monster is fighting. The monster will be accessing all methods needed for fighting. When the monster dies because his health drops to 0, the monsters state will change to dead and your character will stop attacking automatically. This methodology is very similar to using flags or even keywords.

    Also apparently in python deleting classes is not required since they will be garbage collected automatically when they are not used anymore.

提交回复
热议问题