无法理解python __del__的行为

时间:2015-07-12 03:43:58

标签: python del

我有一些测试代码如下,我希望调用__del__函数就像调用del一样。

class MyClass(object):
"""docstring for MyClass"""
    count = 0
    def __init__(self):
        super(MyClass, self).__init__()
        MyClass.count += 1
        print "init instance, total {0}".format(MyClass.count)

    def __del__(self):
        MyClass.count -= 1
        print "del instance, total {0}".format(MyClass.count)

if __name__ = '__main__':
    first_object = MyClass()
    second_object = MyClass()
    # del second_object

我收到以下错误:

init instance, total 1
init instance, total 2
del instance, total 1
Exception AttributeError: "'NoneType' object has no attribute 'count'" in <bound method MyClass.__del__ of <__main__.MyClass object at 0x100f17d10>> ignored

如果我启用以下行,它可以正常工作。

del second_object 

0 个答案:

没有答案