4

This works as expected: a class-level variable a is created with the value 12.

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

But when I try to do the same thing inside a 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

Yet this works without error:

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

What's going on? (This is Python 2.7).

Eli Rose
  • 6,788
  • 8
  • 35
  • 55

1 Answers1

4

When you refer to the variable inside the class body, it is looked up in the global scope, regardless of where the class is defined.

The scope of the function parameter is the body of the function, not the global scope, hence the error.

>>> a = 12
>>> def f(a):
...     class C:
...         a = a
...     print(C.a)
... 
>>> f(42)
12