3

我正在尝试对类 obj 破坏进行一些活动。如何在 _del__ 函数中打开文件?(我正在使用 Python 3.4)

class iam(object):

    def __init__(self):
        print("I m born")

    def __del__(self):
        f = open("memory_report.txt", "w")
        f.write("He gone safe")
        f.close()

if __name__ == '__main__':
    i = iam()
    print("Script Ends. Now to GC clean memory")

输出:

I m born
Script Ends. Now to GC clean memory
Exception ignored in: <bound method iam.__del__ of <__main__.iam object at 0x00000000022F1A58>>
Traceback (most recent call last):
  File "F:\Kumaresan\Code\Python\CommonLib\src\kmxPyQt\devConsole3\tet.py", line 14, in __del__
NameError: name 'open' is not defined    
4

4 回答 4

3

下面的代码工作正常。

class iam(object):

def __init__(self):
    print("I m born")

def __del__(self):
    #"open" function still in __builtins__ 
    f = open("memory_report.txt", "w")
    f.write("He gone safe")
    f.close()

def write_iam():
        i=iam()

if __name__ == '__main__':
    write_iam()
    print("Script Ends. Now to GC clean memory")

在这种情况下:

class iam(object):

def __init__(self):
    print("I m born")

def __del__(self):
    #__builtins__.open  has remove 
    f = open("memory_report.txt", "w")
    f.write("He gone safe")
    f.close()

if __name__ == '__main__':
    i = iam()
    print("Script Ends. Now to GC clean memory")

当退出 __main__ 函数时,在 GC 删除“i”实例(执行 i.__delete__)之前,“open”函数已从 __builtins__ 中删除。

于 2014-10-24T09:37:29.833 回答
2

正如其他人所提到的,不要使用 ____del___ 方法来执行此类清理。相反,使用 contextmanagers ( with -statement) 或注册 atexit-handlers。

于 2014-10-24T08:57:28.223 回答
2

问题是,正如 MuSheng 试图解释的那样,在调用your__builtins__之前已将其删除。 __del__

__del__您可以通过将 None 分配给变量来触发自己。

MuSheng的代码可能是这样的:

class iam():
    def __init__(self):
        print("I m born")

    def __del__(self):
        #"open" function still in __builtins__ 
        with open("memory_report.txt", "w") as f:
            f.write("He gone safe")

if __name__ == '__main__':
    i = iam()
    i = None # This triggers `__del__`
    print("Script Ends. Now to GC clean memory")

MuSheng 值得点赞,IMO

于 2016-05-27T16:27:59.510 回答
1

下面是我使用的替代方法 - 使用 atexit 处理程序:

import atexit


class iam(object):

    def __init__(self):
        print("I m born")
        atexit.register(self.cleanup)

    def cleanup(self):
        f = open("memory_report.txt", "w")
        f.write("He gone safe")
        f.close()
        print ("Done")


if __name__ == '__main__':
    i = iam()
    print("Script Ends. Now to GC clean memory")

输出:

I m born
Script Ends. Now to GC clean memory
Done
于 2014-10-24T10:41:23.067 回答