Why does "x = x" give an error in Python classes only when they are defined inside functions?

This works as expected: a class variable is created with a value of 12 .

 >>> a = 12 >>> class K(object): ... a = a ... >>> print Ka 12 

But when I try to do the same inside the function:

 >>> def f(a): >>> class K(object): ... a = a ... >>> f(12) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in f File "<stdin>", line 3, in K NameError: name 'a' is not defined 

However, this works without errors:

 >>> def f(a): ... a = a ... >>> f(12) 

What's happening? (This is Python 2.7).

+4
source share
1 answer

When you reference a variable inside the body of a class, it is scanned in the global scope, regardless of where the class is defined.

The scope of the function parameter is the body of the function, and not the global area, therefore, an error.

 >>> a = 12 >>> def f(a): ... class C: ... a = a ... print(Ca) ... >>> f(42) 12 
+4
source

All Articles