title: Compound assignment to Python class and instance variables
body: <p>I've been trying to understand Python's handling of class and instance variables. In particular, I found <a href="https://stackoverflow.com/questions/68645/python-static-variable/69067#69067">this answer</a> quite helpful. Basically it says that if you declare a class variable, and then you do an assignment to <code>[instance].property</code>, you will be assigning to a different variable altogether -- one in a different namespace from the class variable.</p>
  
  <p>So then I considered -- if I want every instance of my class to have a member with some default value (say zero), should I do it like this:</p>
  
  <pre><code>class Foo:
      num = 0
  </code></pre>
  
  <p>or like this?</p>
  
  <pre><code>class Foo:
      def __init__(self):
          self.num = 0
  </code></pre>
  
  <p>Based on what I'd read earlier, I'd think that the second example would be initializing the 'right' variable (the instance instead of the class variable). However, I find that the first method works perfectly well too:</p>
  
  <pre><code>class Foo:
      num = 0
  
  bar = Foo()
  bar.num += 1 # good, no error here, meaning that bar has an attribute 'num'
  bar.num
  &gt;&gt;&gt; 1
  Foo.num
  &gt;&gt;&gt; 0 # yet the class variable is not modified! so what 'num' did I add to just now?
  </code></pre>
  
  <p>So.. why does this work? What am I not getting? FWIW, my prior understanding of OOP has come from C++, so explanation by analogy (or pointing where it breaks down) might be useful.</p>