Python object deleting itself

后端 未结 14 1998
一向
一向 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'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.

提交回复
热议问题