title: Why can't I change the __class__ attribute of an instance of object?
body: <pre><code>class A(object):
      pass
  
  class B(A):
      pass
  
  o = object()
  a = A()
  b = B()
  </code></pre>
  
  <p>While I can change <code>a.__class__</code>, I can't do the same with <code>o.__class__</code> (it throws a <code>TypeError</code> error). Why?</p>
  
  <p>For example:</p>
  
  <pre><code>isinstance(a, A) # True
  isinstance(a, B) # False
  a.__class__ = B
  isinstance(a, A) # True
  isinstance(a, B) # True
  
  isinstance(o, object) # True
  isinstance(o, A) # False
  o.__class__ = A # This fails and throws a TypeError
  # isinstance(o, object)
  # isinstance(o, A)
  </code></pre>
  
  <p>I know this generally isn’t a good idea, since it can lead to some very strange behaviour if it is handled incorrectly. It's just for the sake of curiosity.</p>