Python object deleting itself

后端 未结 14 1904
一向
一向 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:40

    I can't tell you how this is possible with classes, but functions can delete themselves.

    def kill_self(exit_msg = 'killed'):
        global kill_self
        del kill_self
        return exit_msg
    

    And see the output:

     >>> kill_self
    <function kill_self at 0x02A2C780>
    >>> kill_self()
    'killed'
    >>> kill_self
    Traceback (most recent call last):
      File "<pyshell#28>", line 1, in <module>
        kill_self
    NameError: name 'kill_self' is not defined
    

    I don't think that deleting an individual instance of a class without knowing the name of it is possible.

    NOTE: If you assign another name to the function, the other name will still reference the old one, but will cause errors once you attempt to run it:

    >>> x = kill_self
    >>> kill_self()
    >>> kill_self
    NameError: name 'kill_self' is not defined
    >>> x
    <function kill_self at 0x...>
    >>> x()
    NameError: global name 'kill_self' is not defined
    
    0 讨论(0)
  • 2020-11-27 04:40

    I'm curious as to why you would want to do such a thing. Chances are, you should just let garbage collection do its job. In python, garbage collection is pretty deterministic. So you don't really have to worry as much about just leaving objects laying around in memory like you would in other languages (not to say that refcounting doesn't have disadvantages).

    Although one thing that you should consider is a wrapper around any objects or resources you may get rid of later.

    class foo(object):
        def __init__(self):
            self.some_big_object = some_resource
    
        def killBigObject(self):
            del some_big_object
    

    In response to Null's addendum:

    Unfortunately, I don't believe there's a way to do what you want to do the way you want to do it. Here's one way that you may wish to consider:

    >>> class manager(object):
    ...     def __init__(self):
    ...             self.lookup = {}
    ...     def addItem(self, name, item):
    ...             self.lookup[name] = item
    ...             item.setLookup(self.lookup)
    >>> class Item(object):
    ...     def __init__(self, name):
    ...             self.name = name
    ...     def setLookup(self, lookup):
    ...             self.lookup = lookup
    ...     def deleteSelf(self):
    ...             del self.lookup[self.name]
    >>> man = manager()
    >>> item = Item("foo")
    >>> man.addItem("foo", item)
    >>> man.lookup
     {'foo': <__main__.Item object at 0x81b50>}
    >>> item.deleteSelf()
    >>> man.lookup
     {}
    

    It's a little bit messy, but that should give you the idea. Essentially, I don't think that tying an item's existence in the game to whether or not it's allocated in memory is a good idea. This is because the conditions for the item to be garbage collected are probably going to be different than what the conditions are for the item in the game. This way, you don't have to worry so much about that.

    0 讨论(0)
  • 2020-11-27 04:40
    class A:
      def __init__(self, function):
        self.function = function
      def kill(self):
        self.function(self)
    
    def delete(object):                        #We are no longer in A object
      del object
    
    a = A(delete)
    print(a)
    a.kill()
    print(a)
    

    May this code work ?

    0 讨论(0)
  • 2020-11-27 04:41

    You don't need to use del to delete instances in the first place. Once the last reference to an object is gone, the object will be garbage collected. Maybe you should tell us more about the full problem.

    0 讨论(0)
  • 2020-11-27 04:41

    what you could do is take the name with you in the class and make a dictionairy:

    class A:
      def __init__(self, name):
        self.name=name
      def kill(self)
        del dict[self.name]
    
    dict={}
    dict["a"]=A("a")
    dict["a"].kill()
    
    0 讨论(0)
  • 2020-11-27 04:43

    I am trying the same thing. I have a RPG battle system in which my Death(self) function has to kill the own object of the Fighter class. But it appeared it`s not possible. Maybe my class Game in which I collect all participants in the combat should delete units form the "fictional" map???

       def Death(self):
        if self.stats["HP"] <= 0:
            print("%s wounds were too much... Dead!"%(self.player["Name"]))
            del self
        else:
            return True
    
    def Damage(self, enemy):
        todamage = self.stats["ATK"] + randint(1,6)
        todamage -= enemy.stats["DEF"]
        if todamage >=0:
            enemy.stats["HP"] -= todamage
            print("%s took %d damage from your attack!"%(enemy.player["Name"], todamage))
            enemy.Death()
            return True
        else:
            print("Ineffective...")
            return True
    def Attack(self, enemy):
        tohit = self.stats["DEX"] + randint(1,6)
        if tohit > enemy.stats["EVA"]:
            print("You landed a successful attack on %s "%(enemy.player["Name"]))
            self.Damage(enemy)
            return True
        else:
            print("Miss!")
            return True
    def Action(self, enemylist):
        for i in range(0, len(enemylist)):
            print("No.%d, %r"%(i, enemylist[i]))
        print("It`s your turn, %s. Take action!"%(self.player["Name"]))
        choice = input("\n(A)ttack\n(D)efend\n(S)kill\n(I)tem\n(H)elp\n>")
        if choice == 'a'or choice == 'A':
            who = int(input("Who? "))
            self.Attack(enemylist[who])
            return True
        else:
            return self.Action()
    
    0 讨论(0)
提交回复
热议问题