Closure/method definition question for Python 2.7
Ian Kelly
ian.g.kelly at gmail.com
Mon Mar 10 20:26:27 EDT 2014
On Mon, Mar 10, 2014 at 11:27 AM, Brunick, Gerard:(Constellation)
<Gerard.Brunick at constellation.com> wrote:
> The following code:
>
> ---
> class Test(object):
> x = 10
>
> def __init__(self):
> self.y = x
>
> t = Test()
> ---
>
> raises
>
> NameError: global name 'x' is not defined.
>
> in Python 2.7. I don't understand why. I would assume that when __init__ is being defined, it is just a regular old function and x is a variable in an outer scope, so the function __init__ would close over the variable x. Moreover, the variable x is not being modified, so this should be O.K. For example, the following is fine (if nonsensical):
Class scopes and function scopes are not equivalent; class attributes
are not considered for closures. Only local variables of outer
functions are considered. At the time __init__ is defined the Test
class has not been created yet, and so the variable x is in local
scope then, e.g.:
class Test(object):
x = 10
def __init__(self, y=x):
self.y = y
This works fine, because the x is evaluated when the function is
created, while it's still in local scope. But Python won't create a
closure for it.
More information about the Python-list
mailing list