title: Why does Python destroy class variables before objects?
body: <p>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.</p>
  
  <p>So I understand that a class's destructor can't rely on global variables, including other modules.</p>
  
  <p>But I would have thought that objects of the class would have to be destroyed before the class is destroyed. Apparently not:</p>
  
  <pre><code>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()
  </code></pre>
  
  <p>On Windows 7 x64 Python v2.7.3 I get:</p>
  
  <pre><code>Creating object, there are now 1
  Creating object, there are now 2
  Exception AttributeError: "'NoneType' object has no attribute 'count'" in &lt;bound
   method A.__del__ of &lt;__main__.A object at 0x0234B8B0&gt;&gt; ignored
  Exception AttributeError: "'NoneType' object has no attribute 'count'" in &lt;bound
   method A.__del__ of &lt;__main__.A object at 0x0234BE90&gt;&gt; ignored
  </code></pre>
  
  <p>I understand the implications of <a href="https://stackoverflow.com/questions/865115/how-do-i-correctly-clean-up-a-python-object" title="https://stackoverflow.com/questions/865115/how-do-i-correctly-clean-up-a-python-object">How do I correctly clean up a Python object?</a>. 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?</p>
  
  <p>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?"</p>
  
  <p>(Yes, I understand that this can be rectified using a context manager, or even simply:</p>
  
  <pre><code>del a1
  del a2
  </code></pre>
  
  <p>to destroy the object before the class is destroyed.)</p>