Python how to ensure that __del__() method of an object is called before the module dies?

前端 未结 2 850
名媛妹妹
名媛妹妹 2021-01-13 20:00

Earlier today I asked this question about the __del__() method of an object which uses an imported module. The problem was that __del__() wants to

2条回答
  •  孤独总比滥情好
    2021-01-13 20:06

    Attach a reference to the function with a keyword parameter:

    import os
    
    class Logger(object):    
        def __del__(self, os=os):
            print "os: %s." %os
    

    or bind it to a class attribute:

    import os
    
    class Logger(object):
        def __init__(self):
            self.os = os
    
        def __del__(self):
            print "os: %s." % self.os
    

    By creating a local (enough) reference, Python will not look up os as a global, but with a local reference, which are stored with the instance or with the function itself, respectively.

    Globals are looked up at runtime (which is why the __del__ function in your other question fails if os has already been cleaned up), while a function local is cleared up together with the function object, or in case of a instance attribute, with the instance.

提交回复
热议问题