How to force deletion of a python object?

前端 未结 4 1209
逝去的感伤
逝去的感伤 2020-11-30 19:36

I am curious about the details of __del__ in python, when and why it should be used and what it shouldn\'t be used for. I\'ve learned the hard way that it is n

4条回答
  •  孤城傲影
    2020-11-30 20:03

    In general, to make sure something happens no matter what, you use

    from exceptions import NameError
    
    try:
        f = open(x)
    except ErrorType as e:
        pass # handle the error
    finally:
        try:
            f.close()
        except NameError: pass
    

    finally blocks will be run whether or not there is an error in the try block, and whether or not there is an error in any error handling that takes place in except blocks. If you don't handle an exception that is raised, it will still be raised after the finally block is excecuted.

    The general way to make sure a file is closed is to use a "context manager".

    http://docs.python.org/reference/datamodel.html#context-managers

    with open(x) as f:
        # do stuff
    

    This will automatically close f.

    For your question #2, bar gets closed on immediately when it's reference count reaches zero, so on del foo if there are no other references.

    Objects are NOT created by __init__, they're created by __new__.

    http://docs.python.org/reference/datamodel.html#object.new

    When you do foo = Foo() two things are actually happening, first a new object is being created, __new__, then it is being initialized, __init__. So there is no way you could possibly call del foo before both those steps have taken place. However, if there is an error in __init__, __del__ will still be called because the object was actually already created in __new__.

    Edit: Corrected when deletion happens if a reference count decreases to zero.

提交回复
热议问题