title: Python class instance __dict__ doesn't contain all instance variables. Why?
body: <p>Here's a bit of a newbie Python question about instance variables.</p>
  
  <p>Consider the following Python 2.7 class definition:</p>
  
  <pre><code>class Foo(object):
      a = 1
  
      def __init__(self):
              self.b = 2
  
      def __repr__(self):
              return "%s" % self.__dict__
  </code></pre>
  
  <p>Now, when I create an instance of <code>Foo</code>, <code>Foo.__dict__</code> contains <code>b</code>, but not <code>a</code>.  </p>
  
  <pre><code>&gt;&gt;&gt; x=Foo()
  &gt;&gt;&gt; x
  {'b': 2}
  &gt;&gt;&gt; dir(x)
  ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', 
   '__getattribute__', '__hash__', '__init__', '__module__', '__new__', 
   '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
   '__str__', '__subclasshook__', '__weakref__', 'a', 'b']
  &gt;&gt;&gt; x.__dict__
  {'b': 2}
  </code></pre>
  
  <p>And here I thought I had a pretty good grasp on the Way of the Python.  </p>
  
  <p>What's the difference between <code>x.a</code> and <code>x.b</code>?  As far as I can tell they're both instance variables.</p>
  
  <p><strong>Edit</strong>: OK, re-reading the <a href="http://docs.python.org/tutorial/classes.html#class-objects" rel="nofollow">Python docs</a> I see that <code>Foo.a</code> is a <em>class attribute</em> rather than an instance variable.  Hm... I guess the confusion comes from the fact that I can assign a new value to <code>x.a</code> and the new value only affects the <code>x</code> instance -- I suppose I'm now aliasing a member variable over the top of the <code>Foo.a</code> attribute:</p>
  
  <pre><code>&gt;&gt;&gt; y=Foo()
  &gt;&gt;&gt; y.a = 2
  &gt;&gt;&gt; y
  {'a': 2, 'b': 2}
  &gt;&gt;&gt; x
  {'b': 2}
  &gt;&gt;&gt; x.a
  1
  &gt;&gt;&gt; z=Foo()
  &gt;&gt;&gt; z
  {'b': 2}
  &gt;&gt;&gt; z.a
  1
  &gt;&gt;&gt; Foo.a
  1
  &gt;&gt;&gt; x.a
  1
  &gt;&gt;&gt; y.a
  2
  </code></pre>
  
  <p>So, now I overwrite the previous value of <code>Foo.a</code>, and it affects all instances of <code>Foo</code> that haven't aliased <code>Foo.a</code>:</p>
  
  <pre><code>&gt;&gt;&gt; Foo.a=999
  &gt;&gt;&gt; x.a
  999
  &gt;&gt;&gt; y.a
  2
  </code></pre>