What is the __del__ method, How to call it?

后端 未结 5 2146
广开言路
广开言路 2020-11-22 05:28

I am reading a code. There is a class in which __del__ method is defined. I figured out that this method is used to destroy an instance of the class. However, I

5条回答
  •  清歌不尽
    2020-11-22 06:02

    The __del__ method (note spelling!) is called when your object is finally destroyed. Technically speaking (in cPython) that is when there are no more references to your object, ie when it goes out of scope.

    If you want to delete your object and thus call the __del__ method use

    del obj1
    

    which will delete the object (provided there weren't any other references to it).

    I suggest you write a small class like this

    class T:
        def __del__(self):
            print "deleted"
    

    And investigate in the python interpreter, eg

    >>> a = T()
    >>> del a
    deleted
    >>> a = T()
    >>> b = a
    >>> del b
    >>> del a
    deleted
    >>> def fn():
    ...     a = T()
    ...     print "exiting fn"
    ...
    >>> fn()
    exiting fn
    deleted
    >>>   
    

    Note that jython and ironpython have different rules as to exactly when the object is deleted and __del__ is called. It isn't considered good practice to use __del__ though because of this and the fact that the object and its environment may be in an unknown state when it is called. It isn't absolutely guaranteed __del__ will be called either - the interpreter can exit in various ways without deleteting all objects.

提交回复
热议问题