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).