title: Initializing field outside __init__
body: <p>I need a bit of help to understand how python initialising works. I have a class (Bar) with another class (Foo) as a field/variable. When I try to initialise this variable directly in Bar (not in the class __init__) all instances of Bar will point to the same Foo. But if I have an __init__ method, as in Bar2, each Bar2 instance will have a unique Foo instance. What is happening here?</p>
  
  <pre><code>class Foo():
      number = 0
  
  class Bar():
      foo = Foo()
  
  class Bar2():
      foo = None
  
      def __init__(self):
          self.foo = Foo()
  
  first = Bar()
  second = Bar()
  
  print "Bar"
  print first
  print second
  print first.foo
  print second.foo
  
  first = Bar2()
  second = Bar2()
  
  print "\nBar2"
  print first
  print second
  print first.foo
  print second.foo
  </code></pre>
  
  <p>The output will for example be:</p>
  
  <pre><code>Bar
  &lt;\__main__.Bar instance at 0x025B2AF8&gt;
  &lt;\__main__.Bar instance at 0x025B2B20&gt;
  &lt;\__main__.Foo instance at 0x004A3AA8&gt;
  &lt;\__main__.Foo instance at 0x004A3AA8&gt;
  
  Bar2
  &lt;\__main__.Bar2 instance at 0x025B2B48&gt;
  &lt;\__main__.Bar2 instance at 0x025B2AF8&gt;
  &lt;\__main__.Foo instance at 0x025B2B70&gt;
  &lt;\__main__.Foo instance at 0x025B2B98&gt;
  </code></pre>
  
  <p>Using Bar both instances will refer to the same Foo instance. Why?</p>
  
  <p><strong>Edit:</strong> Corrected the error with printing <em>first.foo</em> twice for <em>Bar</em>. The resulting behaviour is still as seen in the output.</p>