2

I have some test code as follow, I was expecting the __del__ function should be called as if del is invoked.

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

I am getting the following error:

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

if I enable the following line, it works fine.

del second_object 
senshin
  • 10,022
  • 7
  • 46
  • 59
weiwang
  • 393
  • 3
  • 10
  • 1
    You have probably made some sort of error in paring this code down to produce a small example, since 1.) you have syntax errors (docstring needs to be indented, and you need `== '__main__'`, not `=`; 2.) I cannot reproduce the behavior you describe. – senshin Jul 12 '15 at 03:47
  • `count` exists in `self`, not in `MyClass`, I think? – celticminstrel Jul 12 '15 at 03:48
  • You're making assumptions about the order in which objects are deleted at shutdown time. Those assumptions aren't well-founded. – Charles Duffy Jul 12 '15 at 03:51
  • I cannot reproduce your error message...seems working fine for me ..!...Just fix indentation and add replace `=` with `==` in your last `if __name__ = '__main__':` expression – Iron Fist Jul 12 '15 at 03:59

0 Answers0