Differences between class block and function block in python
<h3>Code 1</h3>

<pre><code>x = 0

class Foo:
    print(x)
    x = 1
    print(x)

print(x)
</code></pre>

<h3>Result 1</h3>

<pre><code>0
1
0
</code></pre>

<hr>

<h3>Code 2</h3>

<pre><code>x = 0

def foo():
    print(x)
    x = 1
    print(x)

foo()
</code></pre>

<h3>Result 2</h3>

<pre><code>UnboundLocalError: local variable 'x' referenced before assignment.
</code></pre>

<hr>

<p>Why can <code>x</code> reference objects from two namespaces in <code>class block</code>?<br>
I don't understand why <code>Code 1</code> not throw an <code>UnboundLocalError</code>.<br>
Inconsistency between function and class bother me.</p>

<hr>

<h2>Update:</h2>

<p>After reading the <a href="http://docs.python.org/py3k/reference/executionmodel.html" rel="nofollow">Python Docs</a> several times, I still cannot understand the scoping rules.</p>

<blockquote>
  <p>The following are blocks: a module, a function body, and a class definition. ...[skip]...</p>
  
  <p>If a name is bound in a block, it is a local variable of that block, unless declared as nonlocal. If a name is bound at the module level, it is a global variable. (The variables of the module code block are local and global.) If a variable is used in a code block but not defined there, it is a free variable.</p>
  
  <p>If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. This can lead to errors when a name is used within a block before it is bound. This rule is subtle. Python lacks declarations and allows name binding operations to occur anywhere within a code block. The local variables of a code block can be determined by scanning the entire text of the block for name binding operations.</p>
</blockquote>
