相关疑难解决方法(0)

如何正确清理Python对象?

class Package:
    def __init__(self):
        self.files = []

    # ...

    def __del__(self):
        for file in self.files:
            os.unlink(file)
Run Code Online (Sandbox Code Playgroud)

__del__(self)上面因AttributeError异常而失败.我理解Python__del__()调用时不保证存在"全局变量"(在此上下文中的成员数据?).如果是这种情况并且这是异常的原因,我该如何确保对象正确破坏?

python destructor

436
推荐指数
10
解决办法
40万
查看次数

我不明白这个python __del__行为

有人可以解释为什么以下代码的行为方式如下:

import types

class Dummy():
    def __init__(self, name):
        self.name = name
    def __del__(self):
        print "delete",self.name

d1 = Dummy("d1")
del d1
d1 = None
print "after d1"

d2 = Dummy("d2")
def func(self):
    print "func called"
d2.func = types.MethodType(func, d2)
d2.func()
del d2
d2 = None
print "after d2"

d3 = Dummy("d3")
def func(self):
    print "func called"
d3.func = types.MethodType(func, d3)
d3.func()
d3.func = None
del d3
d3 = None
print "after d3"
Run Code Online (Sandbox Code Playgroud)

输出(注意d2的析构函数从不被调用)是这个(python 2.7)

delete d1
after d1
func called
after …
Run Code Online (Sandbox Code Playgroud)

python del

33
推荐指数
4
解决办法
4万
查看次数

标签 统计

python ×2

del ×1

destructor ×1