I understand that Python doesn't guarantee the order of destruction of objects at the end of the program, or even that it will happen.
So I understand that a class's destructor can't rely on global variables, including other modules.
But I would have thought that objects of the class would have to be destroyed before the class is destroyed. Apparently not:
class A(object):
count = 0
def __init__(self):
A.count += 1
print 'Creating object, there are now', A.count
def __del__(self):
A.count -= 1
print 'Destroying object, there are now', A.count
a1 = A()
a2 = A()
On Windows 7 x64 Python v2.7.3 I get:
Creating object, there are now 1
Creating object, there are now 2
Exception AttributeError: "'NoneType' object has no attribute 'count'" in <bound
method A.__del__ of <__main__.A object at 0x0234B8B0>> ignored
Exception AttributeError: "'NoneType' object has no attribute 'count'" in <bound
method A.__del__ of <__main__.A object at 0x0234BE90>> ignored
I understand the implications of How do I correctly clean up a Python object?. But this case is for class (shared or 'static' for my C++ friends) variables. Surely the instance has a reference to the class variable, which should not be destroyed first as we still have a reference to it?
Is it a problem or a mistake to have the class destroyed before objects of that class? Maybe my question is 'Where are class-shared variables actually stored?"
(Yes, I understand that this can be rectified using a context manager, or even simply:
del a1
del a2
to destroy the object before the class is destroyed.)